vectorizing four nested for loops

If I have a one-dimensional array A of size n and I need to create a new two-dimensional array R from the elements of array A, I can do it using two nested loops:
for i = 1:n
for j = 1:n
R(i,j) = A(i) + A(j);
end
end
Or I can use vectorization:
[i, j]=ndgrid(1:n);
R = A(i)+A(j);
If array A becomes a n by n matrix and I need to create a four dimensional array R I can still use nested loops:
for i = 1:n
for j = 1:n
for k = 1:n
for l = 1:n
r(i,j, k, l) = a(i, j) + a(k, l);
end
end
end
end
Is there a way to replace these four nested loops and use vectorization? Thanks for your help!

 採用された回答

Geoff
Geoff 2012 年 4 月 3 日

4 投票

Try this:
[i,j] = ndgrid(1:n*n);
r = reshape(a(i)+a(j), [n n n n]);

4 件のコメント

Andrei Bobrov
Andrei Bobrov 2012 年 4 月 3 日
+1
Max
Max 2012 年 4 月 3 日
Thanks a lot for your help, Geoff. Would it be possible to modify your code to accommodate a slightly different manipulation with the matrices in the nested loop:
r(i,j,k,l)=a(i,j)+a(k,l)+a(i+k,j+l) for all i+k<=n and j+l<=n
Thanks!
Geoff
Geoff 2012 年 4 月 3 日
Awwwk!! Um, I dunno. You're talking about chucking in some kind of triangular term. I have trouble thinking about that in 4 dimensions. Remember that brevity should not always be chosen over clarity.
Max
Max 2012 年 4 月 3 日
Yeah, I shouldn't have simplified the problem in the first place. That's my bad. Thanks for your help anyway!

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

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2012 年 4 月 3 日

2 投票

variant
R = bsxfun(@plus,a,reshape(a,1,1,n,n))

1 件のコメント

Max
Max 2012 年 4 月 3 日
Thanks a lot, Andrei!

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

カテゴリ

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

質問済み:

Max
2012 年 4 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by