error with || and && operators in a while loop

5 次查看(过去 30 天)
Hello!
I have written a script in matlab, using the psychophysics toolbox and I keep getting this error
"Operands to the and && operators must be convertible to logical scalar values.
Error in myscript (line 196)
if strcmp(KbName(keyCode), 'm') || strcmp(KbName(keyCode), 'z')
This is the whole while loop in which the error occurs:
% Check the keyboard.
while respToBeMade == true
[keyIsDown, pressedSecs, keyCode] = KbCheck(-1);
if keyIsDown
if strcmp(KbName(keyCode), 'm') || strcmp(KbName(keyCode), 'z')
disp(KbName(keyCode));
respToBeMade = false;
break;
end
end
end
Thanks on advance for your help.
Best,
-Maria

采纳的回答

Guillaume
Guillaume 2017-11-24
编辑:Guillaume 2017-11-24
I don't have the psychotoolbox, but have a look at the documentation of kbCheck.
The reason you get an error is because the keyCode it returns is either empty or more than one value.
If it can be empty, you could change your test to
if ~isempty(keyCode) && ismember(kbName(keyCode), {'m', 'z'})
If it can be more than one value then
if any(ismember(kbName(keyCode), {'m', 'z'}))
or
if all(ismember(kbName(keyCode), {'m', 'z'}))
depending on what you want to test.
Note that
if ismember(kbName(keyCode), {'m', 'z'})
is equivalent to
if strcmp(KbName(keyCode), 'm') || strcmp(KbName(keyCode), 'z')
but obviously less to type and more extensible if you want to add more accepted key codes.
  1 个评论
Maria K
Maria K 2017-11-24
Thanks, I only get the error when I try to log the answers in a text file, but the 'ismember' thing might help me in the future!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Convert Image Type 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by