简体   繁体   中英

Nested loop and conditional statement (Matlab)

If you have a random matrix, for example a 5x5:

A(i,j) = (5 4 3 2 1
          4 3 2 1 0
          5 4 3 2 1
          4 3 2 1 0
          5 4 3 2 1)

And a second array:

B(1,j) = (4 5 6 7 8)

How can I then assign values of B to A if this only needs to be done when the value of B(1,j) is larger than any of the values from a certain colomn of A?

For example, B(1,1) = 4 and in the first colomn of A it is larger than A(1,1), A(3,1) and A(5,1), so these must be replaced by 4. In the second colomn, nothing needs to be replaced, etc.

Thanks already!

You can do this without any explicit looping using bsxfun :

A = [5 4 3 2 1
     4 3 2 1 0
     5 4 3 2 1
     4 3 2 1 0
     5 4 3 2 1];
B = [4 5 6 7 8];

A = bsxfun(@min,A,B);

Result:

A =

   4   4   3   2   1
   4   3   2   1   0
   4   4   3   2   1
   4   3   2   1   0
   4   4   3   2   1

In later versions of MATLAB (2016b and later) you can even omit the bsxfun and get the same result.

A = min(A,B);

Matlab "find" may be of use to you.

https://www.mathworks.com/help/matlab/matlab_prog/find-array-elements-that-meet-a-condition.html

If you aren't concerned about speed or efficiency, you could also set up a two nested for loops with a condition (ie an if) statement comparing the values of A and B.

If you only interested in column wise comparison to B, you could use the increment of the outer loop in the inner loop.

for i,...
 for j,...
   if B(1,i) > A(j,i)
       A(j,i)=B(i,j)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM