This bot开发者_开发技巧hers 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?
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]));
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.
Another way is to repeat vector to match the matrix by size:
out = out.*shiftdim(repmat(vector(:),[1 size(out(:,:,1))]),1)
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;
精彩评论