how to speed this nested loop or to get it around completely

Hi everybody,
I know that this kind of question was been asked a lot of time here on Matlab Answers, but I am not able to adapt previous answers to my problem.
In practice, I testing for a simple trading strategy that goes long when some technical indicators fulfill the relative conditions and close the position when the current price hit the resistance 1.
Anyway, given the following variables:
  • currency: the time series of the closing price of the currency;
  • signal: dummy variable that indicates if you've to assume long position (=1) or not (=0);
  • price: the price at which you buy the currency;
  • exitprice: price at which I will close the long position;
  • resistance: price level at which you find a resistance, computed using the standard pivot point method;
my piece of code is the following one:
for k = 2:length(currency)
if signal(k,:) == 1 && signal(k-1,:) == 0
price(k,:) = currency(k,:);
else price(k,:) = 0;
end
while signal(k,:) == 1
if currency(k,:) == pivotpoints(k,4)
exitprice(k,:) = currency(k,:);
else exitprice(k,:) = 0;
end
end
if signal(k,:) == 0 && signal(k-1,:) == 1
exitprice(k,:) = currency(k,:);
else exitprice(k,:) = 0;
end
end
The problem consists on the fact that running this code Matlab conks out while it runs the while loop. I does not give an error as output, but it cannot finish to run the code.
Does it exist a way to do that in an other way in order to speed the process up?
Thank you all for help!

Answers (1)

Your while loop never comes to an end because the variable k does not change. The loop does not make sense. I have no idea what you want to achieve with the loop but I guess you could do the same without the loop, using vectorization.

3 Comments

Thank Roger for your answer.
I will change the question in the hope to ask it for clearer way.
Anyway, what do you mean when you say "the k-index does not change"?
You never change your while-loop condition within the loop which is :
signal(k,:) == 1
Therefore, once you've entered the loop, you will never get out.
He means your while-loop: you get stuck if signal(k,:) equals 1. In your while-loop the value for k does not change, so you always evaluate the same entry of signal().

Sign in to comment.

Asked:

on 20 Oct 2014

Commented:

on 21 Oct 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!