如何在Matlab中迭代列向量?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在Matlab中,您可以直接迭代列表中的元素。如果您不需要知道当前正在处理哪个元素,这会很有用。
因此,您可以编写
注意,Matlab 会迭代
list
的列,因此如果list
是一个 nx1 向量,您可能需要转置它。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
Note that Matlab iterates through the columns of
list
, so iflist
is a nx1 vector, you may want to transpose it.matlab 中有很多函数,您根本不需要迭代。
例如,乘以它在列表中的位置:
matlab 中的矢量化算法通常要快得多。
with many functions in matlab, you don't need to iterate at all.
for example, to multiply by it's position in the list:
vectorized algorithms in matlab are in general much faster.
如果您只想对每个元素应用函数并将结果放入输出数组中,则可以使用
arrayfun
.正如其他人指出的那样,对于大多数操作,最好避免 MATLAB 和 将您的代码矢量化。
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.