divide matrix by a vector of the same number of column

141 ビュー (過去 30 日間)
em
em 2014 年 11 月 20 日
回答済み: Amirali Kamalian 2019 年 8 月 15 日
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
  1 件のコメント
Jos (10584)
Jos (10584) 2018 年 8 月 1 日
Without logical indexing (and for positive values only):
C = nanmax(A ./ B, 0)

サインインしてコメントする。


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
  1 件のコメント
Jos (10584)
Jos (10584) 2018 年 8 月 1 日
編集済み: Jos (10584) 2018 年 8 月 1 日
Mathematically, this will give the wrong result ...

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by