Indexing matrix using logicals

I'm trying to index a large matrix, with the goal of finding/indexing the first value to meet a threshold. Right now I'm doing it in a loop, but it's rather slow.
For example: a=[10 13 14 15 16;... 11 12 15 16 17;... 3 5 8 9 12]; threshold=11.5;
I want it to return: ans=[2;2;5];
I've tried screwing with find, but all I can seem to get it to return is: ans=[4;5;7;8;10;11;13;14;15];
Thanks, - Matt

답변 (3개)

Matt Fig
Matt Fig 2012년 10월 16일
편집: Matt Fig 2012년 10월 16일

0 개 추천

% Given:
a=[10 13 14 15 16;11 12 15 16 17; 3 5 8 9 12]; % Array
T = 11.5; % Threshold.
% The approach:
L = mod(findstr(reshape(a.',1,numel(a))<T,[1,0]),size(a,2))+1

댓글 수: 6

What if
a=[10 13 14 15 16;11 12 15 16 17; 3 5 8 9 11]; % Array
Matt Fig
Matt Fig 2012년 10월 16일
편집: Matt Fig 2012년 10월 16일
Interesting, what would you expect in that case, Azzi?
Perhaps [2 2 nan] would be most useful?
Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 16일
I prefer [2 2 5],
Matt Fig
Matt Fig 2012년 10월 16일
But from the OP: "with the goal of finding/indexing the first value to meet a threshold"
a(3,5) does not meet the threshold.
Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 16일
Yes, but it's the nearest
To Matt H,
If you want to fill the value with nan (or zero, just replace the nan with 0 in below code) when no member of the row matches, you could use this:
% This array has no element meet the
% threshold in the third row.
a = [10 13 14 15 16;11 12 15 16 17; 3 5 8 9 11];
% So we use NaN as the filler.
[I,J] = find(a>11.5);
A = accumarray(I,J,[size(a,1),1], @min, NaN)

댓글을 달려면 로그인하십시오.

Sean de Wolski
Sean de Wolski 2012년 10월 16일
편집: Sean de Wolski 2012년 10월 16일

0 개 추천

If you can guarantee that each row in A has at least one value greater than the threshold, you can use the index output from max():
a=[10 13 14 15 16; 11 12 15 16 17; 3 5 8 9 12];
thresh = 11.5;
[~,index] = max(a>thresh,[],2);
Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 16일
편집: Azzi Abdelmalek 2012년 10월 16일

0 개 추천

a=[10 13 14 15 16;11 12 15 16 17; 3 5 8 9 12];
[n,m]=size(a)
b=a<11.5
out=arrayfun(@(x) max(find(b(x,:)==1)),1:n)+1
out(out>m)=m
%or
out(out>m)=nan

댓글 수: 1

Another way, just for fun (assuming that each row is sorted, which is assumed if we are interested in the "first" match):
n = size(a,2);
b = a > thresh;
first = n-sum(b,2)+1;
%if first > n, then not found-- set to NaN;
first( first > n)= NaN;

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 NaNs에 대해 자세히 알아보기

질문:

2012년 10월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by