Equivalent to "for" loops on a line by line basis

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

More information about function_x would be necessary to figure out what will be the fastest way to approach the loop issue.
function_x can be any function that performs a mathematical operation on a 1D or 2D set of data and outputs a result. I'm essentially trying to understand to vectorize or to index each line a m x n matrix so that the input to function_x is a single line of the "a" matrix.
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.

Sign in to comment.

Answers (2)

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);
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

Asked:

on 21 May 2011

Community Treasure Hunt

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

Start Hunting!