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.
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)
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With