A matrix operation in MATLAB

2020-04-14 09:29发布

问题:

I am trying to simplify my code a bit, and I am across a small question. Let

v  = [1; 2; 3];
a1 = [4; 5; 6];
a2 = [7; 8; 9];
A  = [a1, a2];

I am aiming to compute

u = [v.*a1, v.*a2]

by only using v one time. Is this possible?

回答1:

yes, you can do this using bsxfun, for example:

u = bsxfun(@times,A,v);

or also by using repmat

u= repmat(v,[1 2]).*A;

or also by using kron

u= kron(v,[1 1]).*A;

or last, just using matrix multiplication:

u = v*[1 1].*A;

I'm sure there are even more ways, but I'll stop here...