简体   繁体   English

嵌套循环和条件语句(Matlab)

[英]Nested loop and conditional statement (Matlab)

If you have a random matrix, for example a 5x5: 如果您有一个随机矩阵,例如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? 如果仅在B(1,j)的值大于A的某个列中的任何值时才需要这样做,我该如何将B的值分配给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. 例如,B(1,1)= 4,并且在A的第一个列中,它大于A(1,1),A(3,1)和A(5,1),因此必须将其替换为4在第二列中,不需要替换任何内容,依此类推。

Thanks already! 已经谢谢你了!

You can do this without any explicit looping using bsxfun : 您可以使用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. 在更高版本的MATLAB(2016b和更高版本)中,您甚至可以省略bsxfun并获得相同的结果。

A = min(A,B);

Matlab "find" may be of use to you. Matlab“查找”可能对您有用。

https://www.mathworks.com/help/matlab/matlab_prog/find-array-elements-that-meet-a-condition.html 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. 如果您不关心速度或效率,也可以设置两个嵌套的for循环,并使用条件(即if)语句比较A和B的值。

If you only interested in column wise comparison to B, you could use the increment of the outer loop in the inner loop. 如果只对与B的列进行比较感兴趣,则可以在内部循环中使用外部循环的增量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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