Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3D Matrix multiplication with vector

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 first layer (all elements) gets multiplied with the first element of the vector and so on...

Now I have to use a function to do it like this:

function out=fun(matrix,vector)

out=matrix;
for k=1:3
    out(:,:,k)=out(:,:,k)*vector(k);
end

Is there a efficient way to do this in just one line without the need for a function?

like image 988
shant Avatar asked Apr 15 '11 19:04

shant


People also ask

Can you multiply matrix with vector?

To define multiplication between a matrix A and a vector x (i.e., the matrix-vector product), we need to view the vector as a column matrix. We define the matrix-vector product only for the case when the number of columns in A equals the number of rows in x.

What is a vector multiplication matrix?

As a “row-wise”, vector-generating process: Matrix-vector multiplication defines a process for creating a new vector using an existing vector where each element of the new vector is “generated” by taking a weighted sum of each row of the matrix using the elements of a vector as coefficients.

How do you multiply a square matrix by a vector?

First, multiply Row 1 of the matrix by Column 1 of the vector. Next, multiply Row 2 of the matrix by Column 1 of the vector. Finally multiply Row 3 of the matrix by Column 1 of the vector.


1 Answers

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]));
like image 136
gnovice Avatar answered Sep 18 '22 16:09

gnovice