7

Lets said I have the matrix M = ones(3); and I want to divide each row by a different number, e.g., C = [1;2;3];.

1 1 1  -divide_by-> 1      1   1   1
1 1 1  -divide_by-> 2  =  0.5 0.5 0.5
1 1 1  -divide_by-> 3     0.3 0.3 0.3

How can I do this without using loops?

MatlabDoug
  • 5,704
  • 1
  • 24
  • 36
adn
  • 897
  • 3
  • 22
  • 49

1 Answers1

6

Use right array division as documented here

result = M./C

whereas C has the following form:

C = [ 1 1 1 ; 2 2 2 ; 3 3 3 ];

EDIT:

result = bsxfun(@rdivide, M, [1 2 3]'); % untested !
zellus
  • 9,617
  • 5
  • 39
  • 56
  • I went through that documentation before. Nevertheless, they explicitly said that both matrix should have the same dimension. Not this being the case. I also was thinking: is it possible to expand the vector to a matrix of the same size to perform element by element division? – adn Oct 15 '10 at 05:43
  • 3
    the first one is basically `M ./ repmat(C,1,3)`. An additional solution is: `M ./ (C*ones(1,3))`, though I prefer to use BSXFUN. – Amro Oct 15 '10 at 13:02