本文介绍了如何将数组与数字进行if语句比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

H0是一个数组([1:10]),而H是一个数字(5).

H0 is an array ([1:10]), and H is a single number (5).

如何将H0中的每个元素与单个数字H进行比较?

How to compare every element in H0 with the single number H?

例如

if H0>H
   do something
else
   do another thing
end

MATLAB总是做另一件事.

MATLAB always does the other thing.

推荐答案

if要求使用以下语句评估标量为true/false.如果该语句是数组,则该行为等同于将其包装在all(..)中.

if requires the following statement to evaluate to a scalar true/false. If the statement is an array, the behaviour is equivalent to wrapping it in all(..).

如果您的比较结果是逻辑数组,例如

If your comparison results in a logical array, such as

H0  = 1:10;
H   = 5;
test = H0>H;

您有两种选择可以通过if语句传递test:

you have two options to pass test through the if-statement:

(1)您可以汇总test的输出,例如,您希望在test中元素的anyall为真时执行if子句,例如

(1) You can aggregate the output of test, for example you want the if-clause to be executed when any or all of the elements in test are true, e.g.

if any(test)
  do something
end

(2)您遍历test的元素,并做出相应的反应

(2) You iterate through the elements of test, and react accordingly

for ii = 1:length(test)
   if test(ii)
      do something
   end
end

请注意,可以通过使用逻辑向量test作为索引来向量化此操作.

Note that it may be possible to vectorize this operation by using the logical vector test as index.

修改

如果(如注释中所示)要P(i)=H0(i)^3 if H0(i)<H,否则要P(i)=H0(i)^2,则只需写

If, as indicated in a comment, you want P(i)=H0(i)^3 if H0(i)<H, and otherwise P(i)=H0(i)^2, you simply write

 P = H0 .^ (H0<H + 2)

这篇关于如何将数组与数字进行if语句比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 02:53