Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare array to a number for if statement?

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.

like image 604
Nawar Avatar asked Dec 03 '12 13:12

Nawar


2 Answers

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)
like image 150
Jonas Avatar answered Oct 27 '22 00:10

Jonas


@Jonas's nice answer at his last line motivated me to come up with a version using logical indexing.

Instead of

for i=1:N
  if H0(i)>H
     H0(i)=H0(i)^2;
  else
     H0(i)=H0(i)^3;
  end
end

you can do this

P = zeros(size(H0)); % preallocate output
test = H0>H;

P(test) = H0(test).^2; % element-wise operations 
                       % on the elements for which the test is true

P(~test) = H0(~test).^3; % element-wise operations 
                         % on the elements for which the test is false

Note that this is a general solution.

like image 39
Barney Szabolcs Avatar answered Oct 27 '22 01:10

Barney Szabolcs