在Matlab中循环使用索引和值的巧妙方法 [英] Neat way to loop with both index and value in Matlab

查看:801
本文介绍了在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 = itemsfor [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.

这篇关于在Matlab中循环使用索引和值的巧妙方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆