Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I divide each row of a matrix by a fixed row?

Tags:

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)?

like image 351
David B Avatar asked Jan 18 '11 12:01

David B


People also ask

How do you divide elements in a matrix?

Description. x = A ./ B divides each element of A by the corresponding element of B . The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.

How do you divide a matrix in R?

R Matrix Division To divide elements of a matrix with the corresponding elements of other matrix, use division (/) operator. The multiplication happens only between the (i,j) of first matrix and (i,j) of second matrix.


2 Answers

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.

like image 181
Itamar Katz Avatar answered Oct 13 '22 19:10

Itamar Katz


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)

like image 42
Amro Avatar answered Oct 13 '22 21:10

Amro