1

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....

Divakar
  • 218,885
  • 19
  • 262
  • 358
horseshoe
  • 1,437
  • 14
  • 42

1 Answers1

1

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)
Community
  • 1
  • 1
Divakar
  • 218,885
  • 19
  • 262
  • 358