How do I find the first instance of consecutive numbers above a threshold in an array?
15 次查看(过去 30 天)
显示 更早的评论
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 个评论
Image Analyst
2015-7-24
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???
采纳的回答
Guillaume
2015-7-24
编辑:Guillaume
2015-7-24
You can use pretty much the same code that you were using. Just change the find condition:
[row, col] = find(A(1:end-1, :) < -400 & A(2:end, :) < -400)
[~, idx] = unique(col, 'first');
rows = row(idx)
A more concise and faster, but more obscure way to do the above three lines is to use max on the logical array:
[~, rows] = max(A(1:end-1, :) < -400 & A(2:end, :) < -400)
更多回答(2 个)
Image Analyst
2015-7-24
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.
0 个评论
Jon
2015-7-23
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')
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!