Why is my if statement breaking when condition is not met?
Show older comments
So I have a program that sets verbose to either 'true' or 'false'
I have the code
if (verbose == 'true')
fprintf('VERBOSE MODE\n');
end
disp(verbose);
If verbose is 'true', there is no problem.
However, if verbose is 'false', my code just quits completely- it won't disp(verbose) for example.
Why is this? I thought my code would just skip over this and continue on if the condition is not fulfilled.
Note: I even tested this by adding in an else statement, and that seems to not even work either. Furthermore, I changed the first line to
if (verbose == 'false')
and I got the right output, so what could be causing the breakdown when the statement is
if (verbose == 'true')
Accepted Answer
More Answers (1)
Steven Lord
on 13 May 2019
'false' is not the same length as 'true' so this will error.
'false' == 'true'
Since you said "my code just quits completely" you must have this block of code wrapped in a try / catch block.
Use isequal or strcmp (or strcmpi if you want case-insensitive comparison) or compare the verbose variable to the string "true" or "false" (note the double quotes.)
verbose = 'false';
willBeFalse(1) = isequal(verbose, 'true');
willBeFalse(2) = strcmp(verbose, 'true');
willBeFalse(3) = verbose == "true"
verbose = 'true';
willBeTrue(1) = isequal(verbose, 'true');
willBeTrue(2) = strcmp(verbose, 'true');
willBeTrue(3) = verbose == "true"
Categories
Find more on Common Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!