If statement with 2 matrices

1 次查看(过去 30 天)
Bas
Bas 2015-10-23
回答: Lessmann 2015-10-23
Hi guys,
I got the following question regarding applying a if statement in the correct way:
I have a matrix A (2856x48) containing values.
I have a matrix B (2856x48) containing ones and zeros.
And I have 2 boundary values C and D.
Now I want to check for each value in A whether it exceeds its corresponding boundary value. And if so, the value in A should be set to the boundary value.
So, let's say the value B(1,1)= 0. In this case the value of A(1,1) should be checked whether it exceeds the boundary value C and if so the value in A(1,1) should be set to C.
Another example, let's say B(2,3)= 1. In this case the value of A(2,3) should be checked whether it exceeds the boundary value D and if so the value in A(2,3) should be set to D.
So boundary value C corresponds to a zero-value in B & D corresponds to a one-value in B.
Can anyone help me out?

采纳的回答

Lessmann
Lessmann 2015-10-23
Hi,
if statements on matrices can often be realized with logical indexing. Assuming the matrix B is of type 'logical', your if statement is:
A(A>D & B) = D
A(A>C & ~B) = C

更多回答(1 个)

Adam
Adam 2015-10-23
Something like this ought to work, though it is untested off the top of my head:
boundaryVals = B * C + ( 1 - B ) * D;
A( A > boundaryVals ) = boundaryVals( A > boundaryVals );

标签

Community Treasure Hunt

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

Start Hunting!

Translated by