Array multiplication along certain dimension?

57 ビュー (過去 30 日間)
Visa Suomi
Visa Suomi 2017 年 11 月 21 日
コメント済み: Visa Suomi 2017 年 11 月 28 日
I have a 4-D array with dimensions A = A1 x A2 x A3 x N and a vector with dimensions V = 1 x N. I would like to multiply each element in the array A with vector V along fourth dimension and take a sum along the same dimension to form a matrix B = A1 x A2 x A3. Currently I am using a loop to achieve this, but is there any faster method to achieve the same result? Thanks!
A1 = 3;
A2 = 3;
A3 = 3;
N = 10;
A = ones(A1, A2, A3, N);
V = ones(1, N);
B = NaN(A1, A2, A3);
for i = 1:A1
for j = 1:A2
for k = 1:A3
B(i,j,k) = squeeze(A(i,j,k,:))' * V';
end
end
end

採用された回答

David Goodmanson
David Goodmanson 2017 年 11 月 24 日
編集済み: David Goodmanson 2017 年 11 月 24 日
Hi Visa,
This seems to work
A1 = 2;
A2 = 3;
A3 = 4;
N = 7;
A = rand(A1, A2, A3, N);
V = rand(1, N);
% ---- method 1
B1 = NaN(A1, A2, A3);
for i = 1:A1
for j = 1:A2
for k = 1:A3
B1(i,j,k) = squeeze(A(i,j,k,:))' * V';
end
end
end
% ---- method 2
D = permute(A,[4 1 2 3]);
E = reshape(D,N,A1*A2*A3);
F = V*E;
B2 = reshape(F,A1,A2,A3);
max(max(max(max(abs(B1-B2))))) ans = 8.8818e-16
  1 件のコメント
Visa Suomi
Visa Suomi 2017 年 11 月 27 日
Hi David,
That works great. Thank you!

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

その他の回答 (1 件)

James Tursa
James Tursa 2017 年 11 月 27 日
Another way:
B = sum(bsxfun(@times,A,reshape(V,1,1,1,numel(V))),4);
Or in later versions of MATLAB:
B = sum(A.*reshape(V,1,1,1,numel(V)),4);
  1 件のコメント
Visa Suomi
Visa Suomi 2017 年 11 月 28 日
Thanks, they work with smaller grids, but I encounter memory problems with my array sizes with these functions. My array A = 120 x 132 x 132 x 120.

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

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by