필터 지우기
필터 지우기

divide matrix by a vector of the same number of column

조회 수: 99 (최근 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 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