mxn and nxn matrix element-wise multiplication without for loop

1 次查看(过去 30 天)
I have 2 2D matrices. First one, A, is mxn where m=n*k and second one, B, is nxn. How do I do element-wise multiplication of every nxn square sub matrix of A with B without for loop? and sum all elements of every multiplied nxn matrix and get a nx1 vector? Below is what I did with for loop. I need to perform the for loop in one row.
n = 10;
k = 5;
A = rand(k*n,n);
B = rand(n,n);
results = zeros(k,1);
for i=1:k
results(i) = sum(B.*A(1+n*(i-1):i*n,:),'all');
end
  6 个评论
Cris LaPierre
Cris LaPierre 2020-10-26
编辑:Cris LaPierre 2020-10-26
What about the requirement to use elementwise multiplication and not use for loops? What about achieving this all in a single row?
ebon T
ebon T 2020-10-26
If the solution can provide all of these then it is perfect! If it is not possible to vectorize then one line of solution also acceptable.

请先登录,再进行评论。

采纳的回答

Bruno Luong
Bruno Luong 2020-10-26
AA = permute(reshape(A,[n,k,n]),[2 1 3]);
results = AA(:,:)*B(:)

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by