Array in IF then Else statement

I want to implement the following statement to my program:
if pinch > 0 then
Dh=h.one-h.two
else Dh=0
end
Howver, pinch = [0:2:10] and matlab only runs it for the first element(0) and not the rest. Any suggestions?

Réponses (2)

the cyclist
the cyclist le 3 Sep 2015

0 votes

If you read the documentation for if, you'll see that when you write
if expression
then the expression has to evaluate to true/false, not a vector of true/false.
There may still be a way to evaluate this in a vectorized manner, though. You have provided quite enough info for us to know what your variables look like, but something like:
D = zeros(size(pinch));
D(pinch>0) = 6;
will work. (You'll need to replace my "6" with an appropriate expression.)
John D'Errico
John D'Errico le 3 Sep 2015
Modifié(e) : John D'Errico le 3 Sep 2015

0 votes

This is a common misperception. What many people fail to understand is that if statements are SCALAR operations. They do not work on every element of an array independently. (Perhaps this is a valid behavior in some other language, that may be.)
If your goal is to operate on an array like this, then you would either use a test inside a loop (not my favorite in general) or you must use a vectorized test and assignment, perhaps like this:
Dh = zeros(size(pinch);
Dh(pinch > 0) = h.one - h.two;

1 commentaire

If h.one and h.two are also vectors, you might need to do
Dh(pinch > 0) = h.one(pinch>0) - h.two(pinch>0)
or whatever it takes to get the properly sized vector. (That is what I meant in my own answer, but did not write out explicitly.)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Question posée :

le 3 Sep 2015

Commenté :

le 3 Sep 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by