8

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?

Community
  • 1
  • 1
gallamine
  • 865
  • 2
  • 12
  • 26
  • 1
    Duplicate: [How to subtract a vector from each row of a matrix?](http://stackoverflow.com/questions/5342857/how-to-subtract-a-vector-from-each-row-of-a-matrix)... which was in turn a duplicate of these (with a different arithmetic operation): [How do I divide matrix elements by column sums in MATLAB?](http://stackoverflow.com/questions/1773099/how-do-i-divide-matrix-elements-by-column-sums-in-matlab), [How can I divide each row of a matrix by a fixed row?](http://stackoverflow.com/questions/4723824/how-can-i-divide-each-row-of-a-matrix-by-a-fixed-row)... Seems to be a very common problem. ;) – gnovice May 11 '11 at 17:08

2 Answers2

14

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.

abcd
  • 41,765
  • 7
  • 81
  • 98
14

bsxfun(.) can potentially be more efficient, but personally as an old timer, I'll would recommend not to totally ignore linear algebra based solutions, like:

> M1= magic(4)
M1 =
   16    2    3   13
    5   11   10    8
    9    7    6   12
    4   14   15    1
> M2= M1(1, :)
M2 =
   16    2    3   13
> M1- ones(4, 1)* M2
ans =
    0    0    0    0
  -11    9    7   -5
   -7    5    3   -1
  -12   12   12  -12

Let the actual use case and profiler to decide the functionality actually utilized.

eat
  • 7,440
  • 1
  • 19
  • 27