1

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?

Amro
  • 123,847
  • 25
  • 243
  • 454
skr
  • 452
  • 6
  • 21

2 Answers2

7

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);
Eitan T
  • 32,660
  • 14
  • 72
  • 109
  • I need a general solution. I read the bsxfun page at MathWorks, but I am not able to understand how do I specify the right indices are multiplied? – skr May 06 '13 at 09:15
  • 1
    @skr This _is_ a general solution, and you don't need to specify anything. `bsxfun` automatically replicates the smaller matrix (in our case `x`) along all non-singelton dimensions of the larger matrix (in our case `A`). So if `x` is a row vector, it will _automatically_ be replicated along the first and the third dimension. – Eitan T May 06 '13 at 09:21
1

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;
Ansari
  • 8,168
  • 2
  • 23
  • 34