Matlab - Quickly subtract [1xN] array from [MxN] matrix elements

gallamine picture gallamine · May 11, 2011 · Viewed 15.4k times · Source

Possible Duplicates:
How to subtract a vector from each row of a matrix?
How can I divide each row of a matrix by a fixed row?

I have matrix (M1) of M rows and 4 columns. I have another array (M2) of 1 row and 4 columns. I'd like to subtract every element in M1 by its respective column element in M2. In other words, each column of M1 needs to be subtraced by the scalar in the same column position in M2. I could call repmat(M2,M,1), which would create a NEW matrix of size MxN, where each element in a column was the same, and then do a element by element subtraction:

M2new = repmat(M2,M,1)
final = M1 - M2new

, however, this is two lines of code and creates a new element in memory. What is the fastest and least memory intensive way of performing this operation?

Answer

abcd picture abcd · May 11, 2011

Use bsxfun like in the following example.

x=magic(4);
y=x(1,:);
z=bsxfun(@minus,x,y)

z =

     0     0     0     0
   -11     9     7    -5
    -7     5     3    -1
   -12    12    12   -12

Here z is obtained by subtracting the first row from every row. Just replace x with your matrix and y with your row vector, and you'r all set.