how to generalize a nested for-loop?2

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

回答 (2 件)

Walter Roberson
Walter Roberson 2015 年 11 月 2 日

1 投票

coeffs = [0.3, 0.2, 0.5, 0.8, 0.1, 0.75]; %for example
V = [1+1i +1-1i -1+1i -1-1i];
n = length(coeffs);
[Vg{1:n}] = ndgrid(V);
Vm = cell2mat( cellfun(@(C) C(:), Vg, 'Uniform', 0) );
t_h1 = Vm * coeffs(:);
h1 = reshape(t_h1, length(V) * ones(1,n));
clear n Vg Vm t_h1

1 件のコメント

Mnr
Mnr 2015 年 11 月 2 日
編集済み: Image Analyst 2015 年 11 月 4 日
It works for any sizes of coeffs! Thank you!

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

Stephen23
Stephen23 2015 年 11 月 2 日

1 投票

@Mnr: try this:
V = [1+1i,+1-1i,-1+1i,-1-1i];
W = [0.3,0.2,0.5,0.8];
N = numel(V);
X = cell(1,N);
[X{:}] = ndgrid(V);
Y = cat(N+1,X{:});
S = [ones(1,N),N];
Z = sum(bsxfun(@times,reshape(W,S),Y),N+1);

4 件のコメント

Mnr
Mnr 2015 年 11 月 2 日
Thank you!
Stephen23
Stephen23 2015 年 11 月 2 日
編集済み: Stephen23 2015 年 11 月 2 日
What do you mean "the original form"? What are you observing? How are you checking this? What code you are using?
When I run my code above and the code given by Walter Roberson in his answer to your earlier question and then compare the outputs:
>> isequal(h1,Z)
ans = 1
this tells us that their outputs are exactly the same size and contains exactly the same values. They cannot be any more similar than this!
Mnr
Mnr 2015 年 11 月 2 日
I checked again and deleted my comment few minutes after I typed it. I do not know why it is still shown to you. Thank you, they are equal and your method is fantastic. Is there a way to accept both the two answers?
Stephen23
Stephen23 2015 年 11 月 2 日
I believe only one answer can be accepted.

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

カテゴリ

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

タグ

質問済み:

Mnr
2015 年 11 月 2 日

編集済み:

2015 年 11 月 4 日

Community Treasure Hunt

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

Start Hunting!

Translated by