a simpler way of doing a nested loop

Hello,
Is there a more efficient alternative way that does the same function as:
V=[1+1i +1-1i -1+1i -1-1i];
for m1=1:length(V)
a=V(m1);
for m2=1:length(V)
b=V(m2);
for m3=1:length(V)
c=V(m3);
for m4=1:length(V)
d=V(m4);
h=[.3 .2]*[a b].'+[.5 .8]*[c d].';
h1(m1,m2,m3,m4)=h;
end
end
end
end
Thanks.

3 件のコメント

Stephen23
Stephen23 2015 年 11 月 1 日
This is what you need to read and understand:
Mnr
Mnr 2015 年 11 月 1 日
Thanks.
Stephen23
Stephen23 2015 年 11 月 2 日

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

 採用された回答

Walter Roberson
Walter Roberson 2015 年 10 月 31 日

3 投票

V=[1+1i +1-1i -1+1i -1-1i];
[A,B,C,D] = ndgrid(V);
h1 = 0.3*A + 0.2*B + 0.5*C + 0.8*D;

5 件のコメント

Mnr
Mnr 2015 年 10 月 31 日
Thank you, but does not give the same answer.
Walter Roberson
Walter Roberson 2015 年 10 月 31 日
I just tried it and it gives an exact identical answer, not a single bit difference.
Mnr
Mnr 2015 年 10 月 31 日
oh sorry. I did not clear the memory. Thank you for your help.
Mnr
Mnr 2015 年 11 月 1 日
Is there is a way of writing this code in a more general form such that it works for different sizes of V? Thank you.
Stephen23
Stephen23 2015 年 11 月 2 日
編集済み: Stephen23 2015 年 11 月 2 日
@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);

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

その他の回答 (1 件)

Jan
Jan 2015 年 10 月 31 日
編集済み: Jan 2015 年 11 月 1 日

3 投票

I prefer Walter's solution, because it is nice. But it is worth to mention, that a pre-allocation improves the loop version. Replacing the dot-product by direct algebra and avoiding repeated calculations improves the speed also:
V = [1+1i, 1-1i, -1+1i, -1-1i];
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
Timings for 5000 repetitions, Matlab R2011b/64/Win7:
Original: 8.90 sec
Walters ndgrid: 1.47 sec
Loop, pre-allocation, inlined dot products: 0.34 sec

2 件のコメント

Mnr
Mnr 2015 年 11 月 1 日
Thank you so much!
Mnr
Mnr 2015 年 11 月 1 日
Is there is a way of writing this code in a more general form such that it works for different sizes of V? Thank you.

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

タグ

質問済み:

Mnr
2015 年 10 月 31 日

コメント済み:

2015 年 11 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by