I have Matlab code below. The variable "k" can be assigned values, 1, 2, 3 or 'N'. Based on the value of "k" I need to execute subsequent if statements. I thought Matlab would not execute the if statements below and return values k1=k2=0 but it does something different. When I issue "whos" command I see the variable types Matlab generated. Can you please help me understand what Matlab is trying to do? How else can I compare/achieve what I am trying to do?
Matlab code
k = 'N'
k1=0;
k2=0;
if k >= 1
k1 = 1;
end
if k >= 2
k2 = 2;
end
k1
k2
Matlab output
k =
'N'
k1 =
1
k2 =
2
Using
ischar()
Function as CheckOne method could be by adding a wrapping/outer if-statement to check that
k
is not a char (character) before evaluating the other two inner if-statements. The functionischar()
will evaluate to "true" if variablek
(the input) is a char (character) and false otherwise. In this case, we use the~
tilde to indicate the not/complement of the result. This inverts the case and~ischar(k)
will evaluate to "true" when the variablek
(the input) is not a char (character). In short, the guarding/outer if-statement can be read as "Ifk
is not a char proceed within the statement".Ran using MATLAB R2019b