3D Matrix multiplication with vector

前端 未结 4 510
一生所求
一生所求 2020-12-10 05:22

This bothers me a bit:

Suppose you have a matrix with three layers.

Is there a simple way to multiply this matrix with a vector of three elements so that the

相关标签:
4条回答
  • 2020-12-10 05:53

    One very terse solution is to reshape vector into a 1-by-1-by-3 matrix and use the function BSXFUN to perform the element-wise multiplication (it will replicate dimensions as needed to match the sizes of the two input arguments):

    newMatrix = bsxfun(@times,matrix,reshape(vector,[1 1 3]));
    
    0 讨论(0)
  • 2020-12-10 05:58

    Another way is to repeat vector to match the matrix by size:

    out = out.*shiftdim(repmat(vector(:),[1 size(out(:,:,1))]),1)
    
    0 讨论(0)
  • 2020-12-10 06:02

    There's a matlab function called repmat that'll help you in this.

    M = [1 2 3]
    M * repmat([1 2 3], 3,1)
    ans =
    
     6    12    18
     6    12    18
     6    12    18
    
    M = [1 2 3]
    M .* repmat([1 2 3], 3,1)
    ans =
    
     1     4     9
     1     4     9
     1     4     9
    

    Depending on how exactly you want to organise your matrices.

    0 讨论(0)
  • 2020-12-10 06:06

    In addition to gnovice's answer, you can also replicate your vector along the other dimensions and do a direct element wise multiplication.

    A=randn(1000,1000,3);%# this is your matrix
    vector=[1,2,3];%# this is your vector
    
    [dim1 dim2 ~]=size(A);
    replicatedVector=repmat(reshape(vector,1,1,3),[dim1,dim2,1]);
    out=A.*replicatedVector;
    
    0 讨论(0)
提交回复
热议问题