Search code examples
matlabpsychtoolboxmodulo

Checking if a number is divisible by 20 MATLAB


The code below will not work because the program won't know if the trial number we are on is divisible by 20. Basically, I want to check if the trial = 20, 40, 60, etc. and if so, have the subject take a break if they wish.

numTrials = 345;

for trial = 1:ntrials

% Take a break every 20 trials, subject can press space key to move on
 if mod(trial, 20) == 0
     breakText = ['Take a break or press the spacebar to continue'];
     tic
     while doc < 30 && ~keyPress
         DrawFormattedText(window, breakText, 'center', 'center', black)
         Screen('Flip', window);
         if (keyCode(spaceKey) == 1)
             break;
         end
     end

end

Thanks in advance!


Solution

  • You can use either mod or rem to determine if a number is divisible by another. For positive numbers, they both return the remainder after dividing two numbers. If a number is perfectly divisible by another, the remainder will be zero.

    is_divisible_by_20 = rem(number, 20) == 0
    

    This will evaluate to true for numbers which are perfectly divisible by 20 so you can put it in place of the condition on the if statement.

    if rem(number, 20) == 0
        % Take a break
    end