Equivalent to "for" loops on a line by line basis
Mostrar comentarios más antiguos
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 comentarios
Matt Fig
el 21 de Mayo de 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
el 21 de Mayo de 2011
Matt Fig
el 21 de Mayo de 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.
Respuestas (2)
Walter Roberson
el 21 de Mayo de 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
el 21 de Mayo de 2011
0 votos
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.
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!