在Matlab中循环使用索引和值的巧妙方法
我的很多循环看起来像这样:
A lot of my loops look like this:
items = [3,14,15,92];
for item_i = 1:numel(items)
item = items(item_i);
% ...
end
这对我来说有点混乱.是否有一些循环构造可让我循环浏览项目并同时携带索引?
This looks a bit messy to me. Is there some loop construct that lets me loop through the items and carry the index at the same time?
我正在寻找一种类似于for item_i as item = items
或for [item_i item] = items
的语法.
I'm looking for a syntax along the lines of for item_i as item = items
or for [item_i item] = items
.
类似于克里斯·泰勒(Chris Taylor)的答案,您可以执行以下操作:
Similar to Chris Taylor's answer you could do this:
function [ output ] = Enumerate( items )
output = struct('Index',num2cell(1:length(items)),'Value',num2cell(items));
end
items = [3,14,15,92];
for item = Enumerate(items)
item.Index
item.Value
end
枚举功能需要更多的工作才能通用,但这只是一个开始,确实适用于您的示例.
The Enumerate function would need some more work to be general purpose but it's a start and does work for your example.
这对于小型向量来说可以,但是您不希望对任何较大的向量执行此操作,因为性能会成为问题.
This would be okay for small vectors but you wouldn't want to do this with any sizable vectors as performance would be an issue.