I am looking for a faster way to use the find command without loops and nothing that I have found so far has helped me. Here is a simplified example of what I am trying to do:
A = [0.1,0.8,1;
0.3,0.7,1;
0.2,0.3,1]; % this is a square matrix with cumulated sums of probabilities in its rows
row_sel = [2,3,2]; % this is a vector containing the rows of A that I am interested in
index = NaN(length(A),1);
for i = 1:length(A)
index(i) = find(A(row_sel(i),:)>rand,1,'first'); % I want to get the index of the first column of row row_sel(i) whose element exceeds a random number
end
Unfortunately, something like
index_mat = find(A(row_sel,:)>rand(length(A),1),1,'first')
does not do the trick. Thanks for any help!
You can compare A indexed by row_sel_ with a column vector of random values, exploiting implicit expansion; and then use the second output of max, which gives the index of the first maximum value along the specified dimension:
[~, index] = max(A(row_sel,:) > rand(numel(row_sel),1), [], 2);
For Matlab before R2016b there is no implicit expanstion, but you can use bsxfun:
[~, index] = max(bsxfun(@gt, A(row_sel,:), rand(numel(row_sel),1)), [], 2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With