using multiple if statement to replace values from another matrix
2 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Walter Roberson
on 12 Mar 2017
Your line
C(k,4:13) == A(l,4:13);
is a comparison, not an assignment.
2 Comments
Walter Roberson
on 12 Mar 2017
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) );
See Also
Categories
Find more on MATLAB Report Generator in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!