find first value below a minimum in a vectorized way
23 次查看(过去 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
0 个评论
采纳的回答
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 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!