Ramakrishnan Kannan
Ramakrishnan Kannan

Reputation: 624

index of first greater than during two array comparison

I have two arrays threshold and values.

threshold=[10 22 97]  
values=[99 23 77 11 8 10]  

I want to output idx such that threshold(idx-1)<values(i)<=threshold(idx). That is for the above example output will be

output=[4 3 3 2 1 1]  

The naive code that can produce above output will be

output=ones(1,length(values))*(length(values)+1); 
for i=1:length(values)  
  for j=1:length(threshold)  
    if(values(i)>threshold(j))  
       output(i)=j;
    end  
  end  
end   

Is there a simple way of doing it. I want to avoid loops.

Upvotes: 2

Views: 82

Answers (2)

Shai
Shai

Reputation: 114826

You can use histc command, with a slight adjustment of threshold array

>> threshold=[-inf 10 22 97 inf];
>> values=[99 23 77 11 8 10]; 
>> [~, output] = histc( values, threshold+.1 )
output =

 4     3     3     2     1     1

The modification of threshold is due to "less-than"/"less-than-equal" type of comparison for bin boundary decisions.

Upvotes: 3

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

No loops often means you'll gain speed by increasing peak memory. Try this:

threshold = [10 22 97];
values    = [99 23 77 11 8 10];

%// Do ALL comparisons
A = sum(bsxfun(@gt, values.', threshold));

%// Find the indices and the ones before 
R = max(1, [A; A-1]);

%// The array you want
R(:).'

If you run out of memory, just use the loop, but then with a find replacing the inner loop.

Loops aren't all that bad, you know (if you have MATLAB > R2008). In theory, the solution above shouldn't even be faster than a loop with find, but oh well...profiling is key :)

Upvotes: 2

Related Questions