Reputation: 607
I'm using a Xeon quad-core processor with 64GB of RAM. The program running the function only has 89 data points. It's now been over 20 minutes and MATLAB is still "busy" computing the program. Does my code below reveal any reason why it's taking so long to compute?
function last15MinsOfDay=last15MinsOfDay(time,price)
% last15MinsOfDay takes the average of prices between 3:45 and 4:00.
timeStr=cellstr(datestr(time));
timeDbl=datevec(timeStr);
times=and(timeDbl(:,4)==14,timeDbl(:,5)>=45)+and(timeDbl(:,4)==15,timeDbl(:,5)==0);
priceIdx=find(times);
z=find(fwdshift(1,priceIdx)~=priceIdx+1);
z=[1; z];
mu=zeros(length(z),1);
for i = 1:length(z);
while i < length(z)
mu(i)=mean(price(priceIdx(z(i):z(i+1))));
end
end
last15MinsOfDay=mu;
Upvotes: 0
Views: 69
Reputation:
To supplement esm's answer, you have two loops, each using the same variable i
, so this will cause an error in your while loop, as the variable i
is redefined by the for loop over each iteration (after you applied esm's correction). To see an example of what I mean, try to following code and look at the output:
z = 1:10;
for i = 1:(length(z));
while i < length(z)
disp(['while loop:' num2str(i)]);
i = i+1;
end
disp(['for loop:' num2str(i)]);
end
Furthermore, because of the dual loops, your wasting a lot of processing time by rewriting the same data to the variable m(i)
I have a feeling this is what you were intending to do:
for i = 1:length(z)-1;
mu(i)=mean(price(priceIdx(z(i):z(i+1))));
end
I just removed the nested while loop, as it doesn't really serve a purpose and eats up processing time and then I changed length(z)
to length(z) - 1
to avoid an index out of bounds
error.
And finally, your script will only use one of your processor cores, so having a qaud core processor here isn't giving you any speed advantages. To use all 4 cores, try using a parfor
instead of for
and you can theoretically quadruple your processing speed.
http://nl.mathworks.com/help/distcomp/parfor.html
Upvotes: 3
Reputation: 4079
I am no expert in matlab but this part looks funny:
for i = 1:length(z);
while i < length(z)
mu(i)=mean(price(priceIdx(z(i):z(i+1))));
end
end
Specifically I do not see i
being incremented in the inner loop so the inner loop will run indefinitely.
Upvotes: 4