Search code examples
matlabcomparevariable-types

Matlab: Comparing different variable types


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

Solution

  • Using ischar() Function as Check

    One 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 function ischar() will evaluate to "true" if variable k (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 variable k (the input) is not a char (character). In short, the guarding/outer if-statement can be read as "If k is not a char proceed within the statement".

    k = 'N';
    k1=0;
    k2=0;
    
    if ~ischar(k)
    if k >= 1 
    k1 = 1;
    end
    
    if k >= 2 
    k2 = 2;
    end
    end
    
    k1
    k2
    

    Ran using MATLAB R2019b