57

Possible Duplicate:
How do I iterate through each element in an n-dimensional matrix in MATLAB?

I have a column vector list which I would like to iterate like this:

for elm in list
   //do something with elm

How?

Community
  • 1
  • 1
snakile
  • 52,936
  • 62
  • 169
  • 241
  • I'll also have you know, googling the terms "iterate over matrix matlab" returns stackoverflow as the number 2 result. – James Aug 11 '10 at 18:22

4 Answers4

101

In Matlab, you can iterate over the elements in the list directly. This can be useful if you don't need to know which element you're currently working on.

Thus you can write

for elm = list
%# do something with the element
end

Note that Matlab iterates through the columns of list, so if list is a nx1 vector, you may want to transpose it.

Jonas
  • 74,690
  • 10
  • 137
  • 177
  • Also not good if you want to change the value of the containing elements – greg121 Feb 08 '14 at 22:19
  • 5
    If you don't know whether list is a column or a row vector, you can use the rather ugly combination `(:)'`: `for elm = list(:)'; %... ;end`. The combination `(:)'` will create row vectors from matrices too, so handle with care. – JaBe Oct 29 '14 at 15:07
  • 1
    you mean `(:).'` right? Otherwise you are using the complex conjugate operator instead of the transpose operator. –  Feb 20 '17 at 15:22
  • @SembeiNorimaki: If you know that your data do not contain complex numbers, `(:)'` will work just fine - though it may be good practice to use `(:).'` regardless. – Jonas Feb 20 '17 at 15:26
31
for i=1:length(list)
  elm = list(i);
  //do something with elm.
James
  • 2,454
  • 1
  • 22
  • 22
6

with many functions in matlab, you don't need to iterate at all.

for example, to multiply by it's position in the list:

m = [1:numel(list)]';
elm = list.*m;

vectorized algorithms in matlab are in general much faster.

Marc
  • 3,259
  • 4
  • 30
  • 41
2

If you just want to apply a function to each element and put the results in an output array, you can use arrayfun.

As others have pointed out, for most operations, it's best to avoid loops in MATLAB and vectorise your code instead.

del
  • 6,341
  • 10
  • 42
  • 45