find first value below a minimum in a vectorized way
25 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
0 Commenti
Risposta accettata
José-Luis
il 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);
Più risposte (1)
Wayne King
il 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.
0 Commenti
Vedere anche
Categorie
Scopri di più su Shifting and Sorting Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!