MATLAB: How to select a random element from each column of an array, ignoring zeros

arraysnanrandom

I have an array of m*n elements, some of them zeros, for example:
A = [1 0 2 3; 0 1 5 6; 0 0 0 4]
I would like to draw randomly, one single non- zero element from each column. one such vector could be:
[1 1 2 6] for example.
I have tried replacing zeros with nan's and using the datasample function to do this, but it does not ignore nan's.
is there a simple way to do this without a loop?
thanks

Best Answer

B = A;
B(B==0) = NaN;
B = sort(B,1);
[~,rlast] = max(B,[],1);
rrand = ceil(rand(size(rlast)).*rlast);
rval = B(sub2ind(size(B),rrand,1:size(B,2)))