How to iterate over a column vector in Matlab? [duplicate]

核能气质少年 提交于 2019-12-17 22:17:44

问题


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?


回答1:


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.




回答2:


for i=1:length(list)
  elm = list(i);
  //do something with elm.



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/3461509/how-to-iterate-over-a-column-vector-in-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!