function i = multinomialResample(N,w)

%w = w(:) / sum(w); % ensure sum to one;
u = sort(rand(N,1));
cdf = cumsum(w);

i = zeros(N,1);
j = 1;

for k = 1:length(cdf)
    while j <= N && cdf(k)>u(j) 
        i(j) = k;
        j = j + 1;
    end
end