divide matrix by a vector of the same number of column

92 vues (au cours des 30 derniers jours)
em
em le 20 Nov 2014
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 ]

Réponses (5)

Star Strider
Star Strider le 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;

Image Analyst
Image Analyst le 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

Amirali Kamalian
Amirali Kamalian le 15 Août 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.

per isakson
per isakson le 1 Août 2018
Modifié(e) : per isakson le 1 Août 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 commentaire
Jos (10584)
Jos (10584) le 1 Août 2018
Without logical indexing (and for positive values only):
C = nanmax(A ./ B, 0)

Connectez-vous pour commenter.


Vikram Gupta
Vikram Gupta le 1 Août 2018
Modifié(e) : per isakson le 1 Août 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 commentaire
Jos (10584)
Jos (10584) le 1 Août 2018
Modifié(e) : Jos (10584) le 1 Août 2018
Mathematically, this will give the wrong result ...

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by