horseshoe
horseshoe

Reputation: 1477

Vectorize 2D 3D matrix product for speedup

I have the following setup

matrix2D_1 = zeros(40,191);
matrix2D_2 = zeros(40,191);
matrix3D_1 = zeros(40,191,191);
for j = 1:40
    for jw = 1:191
        matrix2D_1(j,jw)  = sum(squeeze(matrix3D_1(j,jw,:))'*matrix2D_2' );
    end
end

so I want the sum of all products of the 3rd dimension of the 3D matrix with the elements of the of the first 2D matrix which is the matrix product in

squeeze(matrix3D_1(j,jw,:))'*matrix2D_2'

The sum of these results shall then be stored in the first 2D matrix. As I have to run this in a large loop this takes the most time in my code. I cant get my head around it how to vectorize it in a more elegant way. Any faster solution would be higly appreciated....

Upvotes: 1

Views: 80

Answers (1)

Divakar
Divakar

Reputation: 221654

Yup! Use matrix-multiplication and reshape magic -

M = size(matrix2D_1,2);
matrix2D_1 = reshape(sum(reshape(matrix3D_1,[],M)*matrix2D_2.',2),[],M)

Or sum and then do matrix-multiplication -

matrix2D_1 = reshape(reshape(matrix3D_1,[],M)*sum(matrix2D_2,1).',[],M)

Upvotes: 1

Related Questions