Automated creation of loops within loops

1 visualización (últimos 30 días)
Jethro G
Jethro G el 11 de Mzo. de 2016
Comentada: Stephen23 el 11 de Mzo. de 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.

Respuestas (1)

Guillaume
Guillaume el 11 de Mzo. de 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

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by