Automated creation of loops within loops

3 views (last 30 days)
Jethro G
Jethro G on 11 Mar 2016
Commented: Stephen23 on 11 Mar 2016
I'l try to explain this as simply as possible.
Is there a way for matlab to automatically create loops within loops given a user input. for example if the user gives the number 4 as an input, matlab creates 4 loops one within each other, each with a different counter.
for i=1:10
for j=1:10
for k=1:10
for n=1:10
% code
Obviously I can do this manually but since the number of loops created depends on the user, and it sometimes can get quite large, I was wondering if there is an automatic way to do it.

Answers (1)

Guillaume
Guillaume on 11 Mar 2016
The generic way of doing this in any language is to have a single loop and a vector of indices. With your loop, you increase the 1st index in the vector until your reach its limit, at which point you increase the next index and reset the first one, then start again with increasing the first one. When the 2nd index reaches its limit, you increase the next one and reset the 1st two, and so on. The only difficulty in programming this is the cascading of the increment.
An easy way to implement this in matlab is to use linear indexing and convert back to individual indices with ind2sub:
indices_bounds = [10 12 15 10]; %for example. the number of elements is the number of indices
indices = cell(1, numel(indices_bounds)); %cell array that contains individual indices
for linearindex = 1 : prod(indices_bounds)
[indices{:}] = ind2sub(indices_bounds, linearindex);
%code that uses cell array indices, e.g.
fprintf('%d\t', indices{:}); fprintf('\n');
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!