Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 833
gallamine Avatar asked May 11 '11 17:05

gallamine


2 Answers

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.

like image 170
abcd Avatar answered Nov 03 '22 09:11

abcd


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.

like image 20
eat Avatar answered Nov 03 '22 09:11

eat