Why is my if statement breaking when condition is not met?

14 visualizzazioni (ultimi 30 giorni)
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')

Risposta accettata

James Tursa
James Tursa il 13 Mag 2019
Modificato: James Tursa il 13 Mag 2019
The == operator is an element-wise operator. You need to use a string comparison function for this. E.g.,
if( strcmpi(verbose,'true') )
That's assuming you really are working with character strings and not logical variables. If verbose is in fact a logical variable, then you would just do this:
if( verbose )
What is class(verbose)?

Più risposte (1)

Steven Lord
Steven Lord il 13 Mag 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"

Community Treasure Hunt

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

Start Hunting!

Translated by