How to efficiently calculate a weighted sum of 3 dimensional matrix through a vector in matlab

A is a 3 dimensional matrix (M*N*K), b is a vector with length K. I need to calculate
, which is a 2 dimensional matrix (M*N). But i don't want to write it by a explicit summation because it is too slow. Is there any way to calculate it efficiently through matlab? Please attach the code if convenience.

3 Comments

%Random data
A = rand(3,4,5);
b = rand(5,1);
C = sum(A.*reshape(b,1,1,[]), 3)
C = 3×4
0.7003 1.2789 0.8012 1.0967 0.6957 0.7521 1.0241 0.7907 0.8766 1.2873 1.2261 1.1794
Your code is very good and concise, bro. But it spends more time than the latter answer below. Thanks for your kindly help.
@Hancheng Zhu If that means you've settled on one of the answers below, please Accept-click one of them.

Sign in to comment.

 Accepted Answer

This uses matrix multiplication so it should be well optimized and fast.
[m,n] = size(A, [1 2]);
C = reshape(A,m*n, []) * B(:);
C = reshape(C, m, n);

Products

Release

R2023a

Asked:

on 17 Nov 2023

Commented:

on 20 Nov 2023

Community Treasure Hunt

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

Start Hunting!