MATLAB Answers

Elementwise Matrix multiplication with a Vector to get a higher dimension Matrix

4 ビュー (過去 30 日間)
Kilian Helfenbein
Kilian Helfenbein 2019 年 12 月 10 日
Commented: Kilian Helfenbein 2019 年 12 月 10 日
Hey everyone :)
I would like to create a 3D Matrix out of a 2D Matrix and a Vector. The first page of the 3D Matrix should be equal to the product of the 2D Matrix times the first element of the Vector and so on.
At the moment my Code works but looks very inefficient to me.
clear variables
A1 = [1 2 3; 4 5 6; 7 8 9];
Asize = size(A1);
V1 = (1:1:3);
lengthV1 = length(V1);
A2 = zeros(Asize(1), Asize(2), lengthV1);
idxi = 1;
for idxV1 = V1
for idxA11 = 1:Asize(1)
for idxA12 = 1:Asize(2)
E1 = A1(idxA11, idxA12);
E2 = E1 * idxV1;
A2(idxA11, idxA12, idxi) = E2;
end
end
idxi = idxi+1;
end
The result is exactly what I want. The problem is that in my real code I get a huge 5D Matrix, which gives me a memory error. How can I make my Code more efficient? I tried to apply Vectorization to this example but failed.
Thank you in advance!

  1 件のコメント

Adam
Adam 2019 年 12 月 10 日
"The problem is that in my real code I get a huge 5D Matrix"
What does this mean? It seems like a fundamental aspect of the problem, but you tag it on the end as a passing comment. If you are trying to multiply a 2d array by a 1d array to expand it to a 3d array where do 5d arrays come in? If you mean you have a 5d array (note: a matrix is 2d by definition in Matlab) to multiply by a 1d array, then I suggest you make this the focus of the question as answers people may give to multiply a 2d by a 1d will not necessarily scale up to 5d.

サインイン to comment.

採用された回答

ME
ME 2019 年 12 月 10 日
I think this should do the trick.
A1 = [1 2 3; 4 5 6; 7 8 9];
Asize = size(A1);
V1 = (1:1:3);
lengthV1 = length(V1);
A2 = zeros(Asize(1), Asize(2), lengthV1);
for i=1:lengthV1
A2(:,:,i) = A1(:,:)*V1(i);
end

  1 件のコメント

サインイン to comment.

More Answers (1)

Stephen Cobeldick
Stephen Cobeldick 2019 年 12 月 10 日
編集済み: Stephen Cobeldick 2019 年 12 月 10 日
"How can I make my Code more efficient?"
A2 = bsxfun(@times,A1,reshape(V1,1,1,[])) % for versions >= R2007a
A2 = A1 .* reshape(V1,1,1,[]) % for versions >= R2016b

  1 件のコメント

Kilian Helfenbein
Kilian Helfenbein 2019 年 12 月 10 日
It looks so simple when you see the solution :D Thanks :)

サインイン to comment.

サインイン してこの質問に回答します。

製品


リリース

R2019b

Translated by