Clear Filters
Clear Filters

find first value below a minimum in a vectorized way

18 views (last 30 days)
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

Accepted Answer

José-Luis
José-Luis on 2 Apr 2013
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);
  1 Comment
D.J.
D.J. on 2 Apr 2013
Edited: D.J. on 2 Apr 2013
Thank you both for your answers, I will use the one of José-Luis because I think it is more efficient and also give a NaN when it cannot find a minimum.

Sign in to comment.

More Answers (1)

Wayne King
Wayne King on 2 Apr 2013
I'm sure it's not the most elegant way, but
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];
[I,J] = find(A<=4);
B = sortrows([I J]);
[~,ir,~] = unique(B(:,1),'stable');
B = B(ir,:);
The second column of B gives the first index less than or equal to 4.

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!