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
.
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.
Accepted AnswerYou can combine multiple conditions using & (and) and | (or) (&& and || are also things).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With