how to generalize a nested for-loop?

Hello all,
Is there a way to generalize that nested loop so that it works for any sizes of V? Thank you.

 採用された回答

per isakson
per isakson 2015 年 11 月 2 日
編集済み: per isakson 2015 年 11 月 2 日

0 投票

Try
>> tic, for ii = 1:5000, h1 = cssm( 4 ); end, toc
Elapsed time is 0.279794 seconds.
>> tic, for ii = 1:5000, h1 = cssm( 6 ); end, toc
Elapsed time is 0.950556 seconds.
where
function h1 = cssm( N )
% V = [1+1i, 1-1i, -1+1i, -1-1i];
V = rand(1,N)+1i*rand(1,N);
n = length(V);
h1 = zeros(n, n, n, n);
for m1 = 1:n
c = 0.3 * V(m1);
for m2 = 1:n
c = c + 0.2 * V(m2);
for m3 = 1:n
c = c + 0.5 * V(m3);
for m4 = 1:n
h1(m1,m2,m3,m4) = c + 0.8 * V(m4);
end
end
end
end
end
It already works for "any" length of V - or I missed something

3 件のコメント

Mnr
Mnr 2015 年 11 月 2 日
Thank you! It works for any length of V, however, is there a way of generalizing the number of nested loops? In particular, here we have four number of "for" loops as we have h1=zeros(n,n,n,n). what if h1=zeros(n,n,...,n)?
per isakson
per isakson 2015 年 11 月 2 日
Don't know, however you wrote "works for any sizes of V?"
Mnr
Mnr 2015 年 11 月 2 日
Sorry, I should have asked more clearly.

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

その他の回答 (0 件)

カテゴリ

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

質問済み:

Mnr
2015 年 11 月 2 日

コメント済み:

Mnr
2015 年 11 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by