"Subscript indices must either be real positive integers or logicals."

1 view (last 30 days)
Hi, I made a function to pick and extract a random element from a list (cell array). Most of the time it works, and independently it works. But sometimes, when used in a for loop in the main program, after several repetitions it returns the error "Subscript indices must either be real positive integers or logicals." in the line "stimulus = list{1,position};.
function [listnew,stimulus] = listOperation(list)
%number of elements in list
NrOfWords = numel(list);
%pick random word from list
position = round(rand*NrOfWords);
stimulus = list{1,position};
%remove used word from list
listnew = list;
listnew (:,position) = [];
end
I'm pretty sure position is a positive integer, and it still returns the error if I put int16 in front of it to make sure. Could the problem stem from the way the function is used in the main program? I've attached that too if anyone wants to take a look, the crs./vsg commands are for an external visual stimulus generator.
Also probably need to mention that tragically I am using MATLAB2007 and can't do anything about it.

Answers (2)

David Fletcher
David Fletcher on 31 Mar 2018
Edited: David Fletcher on 31 Mar 2018
if the number of words is low (as it would get after a few repetitions) and rand is small, then the index could potentially be 0? Maybe you want ceil instead of round

Star Strider
Star Strider on 31 Mar 2018
An int16 value can still be negative or zero.
If the output of rand is small enough, it could round to zero. A ‘workaround’ might be:
position = round(max([1 rand*NrOfWords]));

Community Treasure Hunt

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

Start Hunting!