Automated creation of loops within loops

3 次查看(过去 30 天)
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.

回答(1 个)

Guillaume
Guillaume 2016-3-11
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by