Equivalent to "for" loops on a line by line basis
Show older comments
Hello:
I'm trying to clean up a code by removing "for" loops for speed purposes. I've seen threads using repmat and such but I'm not sure how to use them.
I'm trying to replicate what is being done on the example bellow:
a = [1 2 3 4;5 6 7 8;9 10 11 12];
for i=1:size(a,1)
b = function_x(a(i,:));
bArray(i,:) = b;
end
where function_x can be any function such as mean, std, diff etc..
Essentially I want a matrix at the end where each row contains the solution of some operation done on each row of matrix A.
I'm fairly inexperienced with Matlab so I trying to get my mindset right as to how I should go about this.
PS I know I should pre-allocate bArray with zeros for speed purposes.
3 Comments
Matt Fig
on 21 May 2011
More information about function_x would be necessary to figure out what will be the fastest way to approach the loop issue.
Carlos C
on 21 May 2011
Matt Fig
on 21 May 2011
I understand that, but what I was saying is that the particular application will make a difference as to whether it is better to keep the loop or not. If you are just trying to learn in general, that's o.k.
Answers (2)
Walter Roberson
on 21 May 2011
arrayfun(@(K) function_x(a(K,:)), 1:size(a,1), 'Uniform', 0)
and then use cell2mat() if you need to.
However, for mean, std, diff, you can much more easily
bArray = mean(a,2);
bArray = std(a,2);
bArray = diff(a,2);
Daniel Shub
on 21 May 2011
0 votes
Loops in MATLAB are a lot faster now then they used to be, especially if you pre-allocate your vector (in this case bArray) to the correct size. As of r2011a, that step is even optional. You should really be asking, with the help of the profiler, if you need to vectorize your code for speed purposes. If your are spending many hours to vectorize code, which is often less readable and less maintainable, to save a few hours/days of run time, it is probably not worth it.
Categories
Find more on Creating, Deleting, and Querying Graphics Objects 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!