function i = myRandomState(p)
%{
return index from a multinomial draw
handcoding to speed things up

Dick Startz
March 2017
%}

nStates = length(p);
if nStates > 3
    i = randomState(p);
else
    u = rand;
    [sortedProbs,indexSortedProbs] = sort(p,'ascend');
    if nStates == 2
        if u < sortedProbs(1)
            i = indexSortedProbs(1);
        else
            i = indexSortedProbs(2);
        end
    else % must be three states
        if u < sortedProbs(1)
            i = indexSortedProbs(1);
            return;
        elseif u < sortedProbs(1) + sortedProbs(2)
            i = indexSortedProbs(2);
            return;
        else
            i = indexSortedProbs(3);
        end     
    end   
end

