How to compare array to a number for if statement?

if-statement, matlab

Solution

`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)<H`, and otherwise `P(i)=H0(i)^2`, you simply write

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

Problem

`H0` is an array (`[1:10]`), and `H` is a single number (`5`). How to compare every element in `H0` with the single number `H`? For example in ``` if H0>H do something else do another thing end ``` MATLAB always does the other thing.

Original source