Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neat way to loop with both index and value in Matlab

Tags:

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?

I'm looking for a syntax along the lines of for item_i as item = items or for [item_i item] = items.

like image 368
Andreas Avatar asked May 06 '13 09:05

Andreas


People also ask

Can the index in a for loop be a variable MATLAB?

Required (static): You cannot index or subscript the loop variable in any way. This restriction is required, because referencing a field of a loop variable cannot guarantee the independence of iterations.

Can you have multiple conditions in a for loop MATLAB?

Accepted AnswerYou can combine multiple conditions using & (and) and | (or) (&& and || are also things).

How do you make two loops in MATLAB?

Nested Loop is a compound statement in Matlab where we can place a loop inside the body of another loop which nested form of conditional statements. As you have known that, Matlab allows you to combine some compound statements like IF, FOR & WHILE inside other compound loops.


1 Answers

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.

like image 183
grantnz Avatar answered Oct 04 '22 12:10

grantnz