find first value below a minimum in a vectorized way

18 次查看(过去 30 天)
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

采纳的回答

José-Luis
José-Luis 2013-4-2
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 个评论
D.J.
D.J. 2013-4-2
编辑:D.J. 2013-4-2
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.

请先登录,再进行评论。

更多回答(1 个)

Wayne King
Wayne King 2013-4-2
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.

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by