divide matrix by a vector of the same number of column

99 次查看(过去 30 天)
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 ]

回答(5 个)

Star Strider
Star Strider 2014-11-20
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;

Image Analyst
Image Analyst 2014-11-20
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

Amirali Kamalian
Amirali Kamalian 2019-8-15
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.

per isakson
per isakson 2018-8-1
编辑:per isakson 2018-8-1
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

Vikram Gupta
Vikram Gupta 2018-8-1
编辑:per isakson 2018-8-1
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

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by