Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From matrix column subtract corresponding vector value

I have a matrix 'x' and a row vector 'v'; the number of elements in the row vector is the same as the number of columns in the matrix. Is there any predefined function for doing the following operation?

for c = 1 : columns(x)
    for r = 1 : rows(x)
        x(r, c) -= v(c);
    end
end
like image 383
Paul Manta Avatar asked Dec 07 '22 12:12

Paul Manta


2 Answers

bsxfun(@minus,x,v)

Here's an octave demonstration:

octave>  x = [1 2 3;2 3 4]
x =

   1   2   3
   2   3   4

octave> v = [2 0 1]
v =

   2   0   1

octave> 
octave> z=bsxfun(@minus,x,v)
z =

  -1   2   2
   0   3   3
like image 102
tmpearce Avatar answered Jan 15 '23 13:01

tmpearce


If you are using Octave 3.6.0 or later, you don't have to use bsxfun since Octave performs automatic broadcasting (note that this is the same as actually using bsxfun, just easier on the eye). For example:

octave>  x = [1 2 3; 2 3 4]
x =

   1   2   3
   2   3   4

octave> v = [2 0 1]
v =

   2   0   1

octave> z = x - v
z =

  -1   2   2
   0   3   3
like image 25
carandraug Avatar answered Jan 15 '23 12:01

carandraug