MATLAB: Filling Matrix with varying random numbers

MATLABmatrix manipulationrandom number generator

How would one fill a matrix with random numbers based on another matrix? I have the matrix M = [6 0 8 5 8 8 8 8 0 8 8; 6 6 8 8 8 0 3 0 0 0 0; 3 6 6 8 0 5 0 0 2 0 0; 6 6 8 3 0 0 0 0 0 0 0; 2 6 8 8 0 0 5 0 0 7 0; 6 7 8 9 0 0 0 5 0 0 0]; and I want to create a new matrix with the same dimensions that creates a random integer between 1 and the listed value in the corresponding position, excluding 0's. It would be simple to do this with a double for loop and randi(), but that method is too slow. Is there some sort of matrix operator/logic/function that could do this? It needs to be a quick method because I'm wanting to do calculations based on these random numbers and then repeat the process to create a histogram of several thousand results.

Best Answer

Considering the constraints (that it has to be a random integer less that or equal to the corresponding element of ‘M’), a single loop will work:
Midx = find(M > 0);
N = zeros(size(M));
for k1 = 1:numel(Midx)
N(Midx(k1)) = randi(M(Midx(k1)));
end