24

Suppose I have a matrix like:

100 200 300 400 500 600
  1   2   3   4   5   6
 10  20  30  40  50  60
...

I wish to divide each row by the second row (each element by the corresponding element), so I'll get:

100 100 100 100 100 100
  1   1   1   1   1   1
 10  10  10  10  10  10
...

Hw can I do it (without writing an explicit loop)?

David B
  • 29,258
  • 50
  • 133
  • 186
  • Similar question: [How do I divide matrix elements by column sums in MATLAB?](http://stackoverflow.com/q/1773099/97160) – Amro Jun 21 '11 at 11:55

3 Answers3

34

Use bsxfun:

outMat = bsxfun (@rdivide, inMat, inMat(2,:));

The 1st argument to bsxfun is a handle to the function you want to apply, in this case right-division.

Itamar Katz
  • 9,544
  • 5
  • 42
  • 74
27

Here's a couple more equivalent ways:

M = [100 200 300 400 500 600
     1   2   3   4   5   6
     10  20  30  40  50  60];

%# BSXFUN
MM = bsxfun(@rdivide, M, M(2,:));

%# REPMAT
MM = M ./ repmat(M(2,:),size(M,1),1);

%# repetition by multiplication
MM = M ./ ( ones(size(M,1),1)*M(2,:) );

%# FOR-loop
MM = zeros(size(M));
for i=1:size(M,1)
    MM(i,:) = M(i,:) ./ M(2,:);
end

The best solution is the one using BSXFUN (as posted by @Itamar Katz)

Community
  • 1
  • 1
Amro
  • 123,847
  • 25
  • 243
  • 454
6

You can now use array vs matrix operations.

This will do the trick :

mat = [100 200 300 400 500 600
     1   2   3   4   5   6
     10  20  30  40  50  60];

result = mat ./ mat(2,:)

which will output :

result =

   100   100   100   100   100   100
     1     1     1     1     1     1
    10    10    10    10    10    10

This will work in Octave and Matlab since R2016b.

Tom
  • 375
  • 1
  • 4
  • 13