MATLAB Answers

Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。

grant
0

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

grant
さんによって質問されました 2019 年 5 月 13 日
最新アクティビティ James Tursa
さんによって 編集されました 2019 年 5 月 13 日
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')

  0 件のコメント

サインイン to comment.

タグ

2 件の回答

回答者: James Tursa
2019 年 5 月 13 日
編集済み: James Tursa
2019 年 5 月 13 日
 採用された回答

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)?

  0 件のコメント

サインイン to comment.


回答者: Steven Lord
2019 年 5 月 13 日

'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"

  0 件のコメント

サインイン to comment.



Translated by