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

5 visualizzazioni (ultimi 30 giorni)
Maria K
Maria K il 24 Nov 2017
Commentato: Maria K il 24 Nov 2017
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

Risposta accettata

Guillaume
Guillaume il 24 Nov 2017
Modificato: Guillaume il 24 Nov 2017
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 Commento
Maria K
Maria K il 24 Nov 2017
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!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Convert Image Type in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by