divide matrix by a vector of the same number of column
92 views (last 30 days)
Show older comments
I have a matrix A[mXn] for example,
A=[ 0 2 0 0 0
0 1 1 0 1
0 1 0 0 2
0 0 0 0 1
0 0 0 0 0]
I have a vector that computes the colume-wise sum of A, B=sum(A,1),
B=[0 4 1 0 4]
How can I compute a matrix C, which each element is the element of A divided by the element of B that is in the same colume? Therefore, my C should be
C=[0 0.5 0 0 0
0 0.25 1 0 0.25
0 0.25 0 0 0.5
0 0 0 0 0.25
0 0 0 0 0 ]
0 Comments
Answers (5)
Star Strider
on 20 Nov 2014
Using bsxfun:
A=[ 0 2 0 0 0
0 1 1 0 1
0 1 0 0 2
0 0 0 0 1
0 0 0 0 0];
B=[0 4 1 0 4];
C = bsxfun(@rdivide, A, B);
C(isnan(C)) = 0;
0 Comments
Image Analyst
on 20 Nov 2014
One way of probably many ways:
A=[ 0 2 0 0 0
0 1 1 0 1
0 1 0 0 2
0 0 0 0 1
0 0 0 0 0]
[rows, columns] = size(A)
% Get sum of columns and replicate vertically.
denom = repmat(sum(A, 1), [rows, 1])
% Do the division.
C = A ./ denom
% Set infinities (where denom == 0) to 0
C(denom==0) = 0
0 Comments
Amirali Kamalian
on 15 Aug 2019
You can also use matrix-matrix multiplication where,
B = B.^(-1);
C = A*diag(B);
C(isnan(C)) = 0;
This code is perhaps easier and computationally more efficient.
0 Comments
per isakson
on 1 Aug 2018
Edited: per isakson
on 1 Aug 2018
I like this better. It avoids dividing by zero.
ispos = B>0
C = A;
C(:,ispos) = A(:,ispos) ./ B(ispos)
Requires "Implicit expansion", which was introduced in R2016b
1 Comment
Jos (10584)
on 1 Aug 2018
Without logical indexing (and for positive values only):
C = nanmax(A ./ B, 0)
Vikram Gupta
on 1 Aug 2018
Edited: per isakson
on 1 Aug 2018
Issue here is divide by 0 is not defined. But if the extremely small change is introduced
>> B=[0 4 1 0 4];
>> B = B +(10^-10)
>> A ./ B
ans =
0 0.5000 0 0 0
0 0.2500 1.0000 0 0.2500
0 0.2500 0 0 0.5000
0 0 0 0 0.2500
0 0 0 0 0
1 Comment
Jos (10584)
on 1 Aug 2018
Edited: Jos (10584)
on 1 Aug 2018
Mathematically, this will give the wrong result ...
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!