Abi
Abi

Reputation: 47

Matlab Operators

I am studying for cumulative exam I have tomorrow and I got the following question wrong on a previous exam. I was hoping someone could explain this question to me? What does (~m) mean?

The question says:
After executing the following script, what is the value of m?

a=1; b=2; m=0;  
if (~m)  
    m = m+1;  
    if (a-b > 0)  
        m = m+1;  
    else  
        m = m -1;  
    end  
elseif (m > 1)  
    m = m + 2;  
else  
    m = m - 2;  
end

The correct answer is 0, but why? I would have guessed that m = -2

Upvotes: 1

Views: 284

Answers (1)

Pursuit
Pursuit

Reputation: 12345

The ~ means NOT. However, numeric values are all considered TRUE unless they are identically equal to 0.

So, the commands which are actually executed by this logic are:

m = m+1;  %Following if (~m)
m = m-1;  $Following else

Also, there is a nested if statement in the code. It will be easier to read if you used multiple level indentations.

Upvotes: 9

Related Questions