create a variable number of nested for loops? select elements in matrix with variables dimensions?

hi,
i have a fucntion with a matrix that has variables dimensions (depends on a parameter given in input) and i would like to scan all the elements inside, but the fact is that i don't know how to nest many for loops.
let´s make an example: M is a matrix 3 dimensional with length [2,4,6]
i would like to do:
for i1:1=2
for i2:1=4
for i3:1=6
M(i1,i2,i3) = 0;
end
end
end
as you can notice, i need 3 loops, but how to use N loops, with N the number of dimensions of M (N is fixed once that function is called)? i thought about using eval, but it seems not working..
another related question, i would like to access to element M(i1,i2,i3) if N=3 or M(i1,i2,i3,i4,i5) if N=5, should i use eval also in this case, or is there any better solution?
thanks in advance

 採用された回答

The particular example you give can be written as
M(1:2,1:4,1:6) = 0;
With regards to the nested loop: turn them into a single loop using an "odometer" type mechanism. See my code in https://groups.google.com/group/comp.lang.c/browse_thread/thread/d98842738fa27a55/2f6d5ff877063de1 and Chris Torek's useful modification there.
With regard to variable number of subscripts:
subs = [i1, i2, i3, i4];
subscell = num2cell(subs);
M(subscell{:})

3 件のコメント

Tom
Tom 2012 年 5 月 30 日
Would it be easier in this case to run through the variables sequentially?
for i=1:numel(M)
M(i)=0
end
If all of the elements are to be set to 0 without disturbing the size or shape, then M(:) = 0 is easier.
Tom
Tom 2012 年 5 月 30 日
Indeed, though in that case it would seem pointless generating the matrix in the first place (or just use the zeros function), so I assume there's some other stuff later in the loop.

サインインしてコメントする。

その他の回答 (2 件)

Andrea
Andrea 2012 年 6 月 8 日
thanks, i didnt have the time to check your discussion..
of course there is much code inside the loops, i wrote m= 0 only to write something random inside
Henry Charlesworth
Henry Charlesworth 2016 年 6 月 30 日
編集済み: Henry Charlesworth 2016 年 6 月 30 日
So you can do it with eval although not sure it's particularly good practice:
%
nLoops=3;
str = '';
for i=1:nLoops
str = sprintf('%s \n for i%d=1:5',str,i);
end
str = sprintf('%s \n [i1 i2 i3]',str);
for i=1:nLoops
str = sprintf('%s \n end',str);
end
eval(str)

1 件のコメント

eval() is not recommended at all. It is fairly prone to mistakes, and always inefficient.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by