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?
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.
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.
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.
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]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With