How to compare array to a number for if statement?

前端 未结 3 1988
礼貌的吻别
礼貌的吻别 2020-12-11 03:30

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

How to compare every element in H0 with the s

3条回答
  •  再見小時候
    2020-12-11 03:58

    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;
    

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

    (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) You iterate through the elements of test, and react accordingly

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

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

    edit

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

     P = H0 .^ (H0

提交回复
热议问题