MATLAB: Find first value below a minimum in a vectorized way

findminimumvectorized

I have a matrix in which I want to find the index per row of the first value that is below a certain threshold. Below is code posted that works but I would like to do it in a vectorized way, I feel this should be possible.
A = [ 5,6,5,2,2,6; 7,6,4,4,2,4;9,5,4,2,4,2;7,6,5,5,4,3;5,6,8,7,8,9] B = zeros(size(A,1),1); minimum = 4 for i = 1:size(A,1) x = find(A(i,:)<= minimum,1,'first'); if isempty(x) B(i) = 0; else B(i) = x; end end B
Thanks in advance for any proposed solution, Dolf

Best Answer

Using only min() and some logical indexing:
A = [ 5,6,5,2,2,6; 7,6,4,4,2,4;9,5,4,2,4,2;7,6,5,5,4,3;5,6,8,7,8,9]
thresh = 4;
temp_mat = repmat(1:size(A,2),size(A,1),1);
temp_mat = temp_mat .* (A<=thresh);
temp_mat(temp_mat == 0) = NaN;
your_idx = min(temp_mat,[],2);