Reputation: 452
Suppose I have a matrix A=rand(2,14,24) and a vector x=10*ones(1,14)
I want element wise multiplication of A and x, such that B(i,j,k)=A(i,j,k)*x(j) for all j=1,2,..14. I want to be able to do this without running a loop. What is the most efficient way to do this in matlab?
Upvotes: 1
Views: 4454
Reputation: 32920
If you're multiplying A
by a vector of 10's element-wise, wouldn't it be easier to simply multiply by a scalar instead?
B = A * 10;
For a general case, there is no need for repmat
logic here. bsxfun
can do the trick (and it's faster). :
B = bsxfun(@times, A, x);
Upvotes: 7
Reputation: 8218
You first use repmat
to tile x
the right number of times, then do element-wise multiplication.
repX = repmat(x, [size(A, 1), 1, size(A, 3)]);
B = A.*repX;
Upvotes: 1