0

I'm trying to substract a 1 x M matrix from a N x M matrix.

lets say my 1 x M matrix is [1 2]

and my N x M matrix is [3 4; 5 4; 1 6]

and what I want as a result is [2 2; 4 2; 0 4]

I know how to do this with a for loop etc, what I'm trying to figure out is is there a math way of doing this in a single line?

Thanks.

Rudithus
  • 183
  • 13

1 Answers1

1

You can use the repmat function to extend your 1xM matrix to NxM and then perform the subtraction.

>> M = [1 2];
>> N = [3 4; 5 4; 1 6];
>> N - repmat(M, length(N), 1)
ans =

     2     2
     4     2
     0     4

Alternatively as pointed out by Divakar you can use

>> bsxfun(@minus, N, M)
ans =

     2     2
     4     2
     0     4
IKavanagh
  • 6,089
  • 11
  • 42
  • 47
  • So I need to construct a matrix with duplicate rows, I get it. Thanks.I was hoping there would be a Math operator for this kind of thing. – Rudithus Sep 21 '15 at 11:41
  • @Rudithus There is : `bsxfun(@minus,matrix,vector)`, also listed in the dup link. `bsxfun` brings your broadcasting/automatic replication and `@minus` is your operator – Divakar Sep 21 '15 at 11:45
  • I think I will go with bsxfun, thanks alot. – Rudithus Sep 21 '15 at 11:51