Search code examples
matlabmatrixsubtraction

MATLAB subtract every row of matrix by a given vector


Let

M = | 1 2 3 |
    | 4 5 6 |
    | 7 8 9 |

and

V = | 1 1 1 |

I want to subtract V from every row of M so that M should look like

M = | 0 1 2 |
    | 3 4 5 |
    | 6 7 8 |

How can I do that without using a for, is there any straightforward command?


Solution

  • >> M = [1 2 3; 4 5 6; 7 8 9];
    >> V = [1 1 1];
    >> MV = M-repmat(V,size(M,1),1)
    
    MV =
    
         0     1     2
         3     4     5
         6     7     8
    

    The call to repmat repeats the vector V by the number of rows in M.

    User beaker pointed out that an even simpler (though a bit obscure) syntax works in recent versions of MATLAB. If you subtract a vector from a matrix, MATLAB will extend the vector to match the size of the matrix as long as one dimension of vector matches the matrix dimensions. See Compatible Array Sizes for Basic Operations.

    >> M-V
    
    ans =
    
         0     1     2
         3     4     5
         6     7     8
    

    Of course, if you know that V will contain all 1s, the solution is even simpler:

    >> MV = M-1
    
    MV =
    
         0     1     2
         3     4     5
         6     7     8