How do I find the first instance of consecutive numbers above a threshold in an array?
Show older comments
I have this code which converts the output of a process i'm running into a table, then to an array, and then finds the first instance that a number crosses a threshold:
T = table(Spots); %convert output of Ornstein-Uhlenbeck process to table
A = table2array(T); %convert table to array
>> [I,J] = find(A<-400); %find first instance of -400 in each column, and report the row position
>> [~,m] = unique(J, 'first');
>> I(m);
The array is 300x4 double and I and J are both 797x1 double.
I am trying to change this to find the first instance of two consecutive numbers below the threshold (-400) and have that reported to me. What would be the best way to go about this?
Thanks,
Mike
2 Comments
Image Analyst
on 24 Jul 2015
Are they all integers? So do you mean like -402 and -401? What does consecutive mean? Separated by exactly 1? What about -514.5 and -513.5? Have you tried the diff() function???
Michael Suffield
on 24 Jul 2015
Accepted Answer
More Answers (2)
Image Analyst
on 24 Jul 2015
If the numbers are integers, this works:
% Create sample data.
A = randi([-444,-430], 10, 10)
% Find the differences from one row to the row below it.
da = diff(A)
% Find which of those have a difference of exactly 1.
consecutive = da == 1
% Go across each column, finding the first consecutive pair
[rows, columns] = size(A);
% Instantiate array to hold our answers
theRows = -1 * ones(rows, 1);
for col = 1 : columns
thisColumn = da(:, col);
% Find the first 1
firstRow = find(thisColumn == 1, 1, 'first');
if ~isempty(firstRow)
fprintf('In column %d, rows %d and %d are consecutive with values of %d and %d.\n', ...
col, firstRow, firstRow+1, A(firstRow, col), A(firstRow+1, col));
theRows(col) = firstRow; % Save the value
else
% No consecutive numbers found
fprintf('No consecutive numbers are in column %d.\n', col);
end
end
% Print to command window:
theRows
Give it a try and see. It's well commented and explicit so it should be easy to follow.
Jon
on 23 Jul 2015
Here's one of many ways, if I understand correctly your question:
thresh = 300;
blah = [100 200 300 400 500 600 700 600 500 400 300 200];
blah2 = blah>thresh;
ur_idx = find(blah2(1:end-1)+blah2(2:end)==2,1,'first')
1 Comment
Michael Suffield
on 24 Jul 2015
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!