필터 지우기
필터 지우기

using multiple if statement to replace values from another matrix

조회 수: 1 (최근 30일)
Phat Pumchawsaun
Phat Pumchawsaun 2017년 3월 12일
댓글: Walter Roberson 2017년 3월 12일
Hi,
I have two matrix (A and B in attached excel file) which have the same dimension (853x13). I would like to use multiple "if" function as following code;
C = zeros(size(B));
for k = 1:length(B);
l = 1:length(A);
if B(k,2) > B(k,3);
if B(k,4:13) > A(l,4:13);
C(k,4:13) == A(l,4:13);
else
C(k,4:13) = B(k,4:13);
end
else
C(k,4:13) = B(k,4:13);
end
end
I want matrix "C" to have both values from A and B if it follows the fist line of if condition. However, the new matrix "C" has values only from matrix B. How should I correct it? Since the length of matrix A and B is so huge, I attached excel file of both matrix.
Thanks

답변 (1개)

Walter Roberson
Walter Roberson 2017년 3월 12일
Your line
C(k,4:13) == A(l,4:13);
is a comparison, not an assignment.
  댓글 수: 2
Phat Pumchawsaun
Phat Pumchawsaun 2017년 3월 12일
편집: Phat Pumchawsaun 2017년 3월 12일
I have changed to;
C(k,4:13) = A(l,4:13);
But, there is still be the same problem.
Walter Roberson
Walter Roberson 2017년 3월 12일
You have
l = 1:length(A);
so l is a vector.
You have
if B(k,4:13) > A(l,4:13);
l is a vector, as indicated above, so A(l,4:13) is indexing A with subscripts that are both vectors. Since l is 1:length(A) then as long as A has more rows than columns, A(l,4:13) means the same as A(:,4:13) does -- a rectangular portion extracted from an array.
Meanwhile, B(k,4:13) is a vector. So your > operator is comparing a vector to a rectangular array. In all versions before R2016b, that would be an error. In R2016b and later, the result is the same as if you had used
if bsxfun(@gt, B(k,4:13), A(l,4:13))
which in turn is the same as
if repmat(B(k,4:13), length(A), 1) > A(l,4:13)
which repeats the row of B into equivalent size of A's rows. You end up with a rectangular matrix ">" a rectangular matrix. The result of that ">" operator is going to be a rectangular matrix of true and false values.
When "if" is asked to process a vector or matrix of true and false values, then it considers the condition to hold only if all of the values are non-zero (true). In your 2D matrix case, that would be equivalent to
if all(all( repmat(B(k,4:13), length(A), 1) > A(l,4:13) ))
And in your case that does not happen to be the case.
My guess at what you want:
nrow = size(B,1);
for k = 1:nrow
if B(k,2) > B(k,3)
C(k,4:13) = min(A(k,4:13), B(k,4:13));
else
C(k,4:13) = B(k,4:13);
end
end
Or in vectorized form with no loop:
C = zeros(size(B));
C(:,4:13) = B(:,4:13);
mask = B(:,2) > B(:,3);
C(mask, 4:13) = min( A(mask,4:13), B(mask,4:13) );

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 MATLAB Report Generator에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by