Other options than loops

5 views (last 30 days)
Zack Bayhan
Zack Bayhan on 14 Dec 2014
Answered: Jan on 14 Dec 2014
Hi everyone, I've read a few times on here that if possible you should avoid using loops. So I was hoping you would be able to look at the code I've attempted to write with loops and give me some possible option to look into which will hopefully make the programming easier and quicker to run when I scale up the size of the matrix involved. I'm still working on some of the logic parts of the code but I'm hoping there will be enough there for you to see what I'm attempting to accomplish.
So basically what happens is it load a file which is attached to the post. I'm trying to use two loops which will extract rows or columns for use in calculations. So the h loop is supposed to work across the stocks array at each iteration converting that array to a matrix so that the i loop can do all the adding and subtracting for the particular calculation. However that's where the logic breaks down and doesn't do what I want but the thought was there.
So for a project like this what are some possible built in matlab commands that may be useful for me to look into? If you have any specific questions for me or need further clarification on what I'm attempting to accomplish with this program please let me know. And as always thanks in advance for taking time to look into this matter.
Zack
clear all
load('Stocks.mat');
count=0;
while count<1;
for h=1:length(Stocks);
Single_out_Array=Stocks{2,h};
array_to_matrix=cell2mat(Single_out_Array);
Closing_Price=array_to_matrix(:,1);
count=1;
if count==1;
for i=1:length(array_to_matrix)-1;
Difference(i)=(Closing_Price(i+1,1)-Closing_Price(1,1));
Percent_Change(i)=((Difference(i))/(Closing_Price(i+1,1)))*100;
xbar(i)=((sum(Percent_Change(i)))/(length(Closing_Price)));
Variance(i)=((sum(Percent_Change-xbar(i)).^2)/length(Closing_Price));
sigma(i)=sqrt(Variance(i));
end
end
end
end

Answers (1)

Jan
Jan on 14 Dec 2014
Since Matlab 6.5, published 12 years ago, loops are processed efficiently. Some functions can operate on a complete array and using loops to process the array element by element are slower. But when larger intermediate arrays are required, it depends on the problem, if loops or vectorized operations are faster.
So in general start with optimizing the loop before you compare the speed with a vectorized version:
  • Omit repeated operations. Move such operations before the loop and store the result in a temporary variable.
  • Pre-allocate vectors instead of letting them grow in each iteration.
  • Reduce the number of calls of external functions.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!