Finding Consecutive values in array that meet specific Criteria?

9 次查看(过去 30 天)
I have a list of values
a = [3 10 7 6 2 3 4 8]
I want to find the longest list of terms where a is greater than a certain threshold. So when a>5. These values would be [10 7 6] for the specific example and I would also like this be the output. Each value is consecutive and greater than the threshold. Although 8 is greater than the threshold, it is not consecutive. I would like to be able to do this without a looping structure if at all possible.

采纳的回答

Matt J
Matt J 2015-2-12
S=regionprops(a>5,'PIxelIdxList','Area');
[~,idx]=max([S.Area]);
longest = a(S(idx).PixelIdxList)

更多回答(2 个)

Azzi Abdelmalek
Azzi Abdelmalek 2015-2-12
a = [3 10 7 6 2 3 4 8 4 2 7 8 9 10 1 2 7]
idx=[0 a>5 0]
ii=strfind(idx,[0 1]);
jj=strfind(idx,[1 0])-1;
[b1,b2]=max(jj-ii+1);
sequence=a(ii(b2):jj(b2))

Image Analyst
Image Analyst 2015-2-12
If you have the Image Processing Toolbox, it's just basically 2 or 3 lines of code : a call to bwlabel and one call to regionprops:
% Check that user has the Image Processing Toolbox installed.
hasIPT = license('test', 'image_toolbox');
if ~hasIPT
% User does not have the toolbox installed.
message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?');
reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes');
if strcmpi(reply, 'No')
% User said No, so exit.
return;
end
end
a = [3 10 7 6 2 3 4 8]
% Threshold greater than 5 and label.
labeled = bwlabel(a > 5)
measurements = regionprops(labeled, a, 'area', 'PixelValues')
% Get all the areas (lengths of runs above threshold).
allAreas = [measurements.Area]
% Sort them in descending order
[sortedAreas, sortIndices] = sort(allAreas, 'Descend')
% Get the values of the data with the longest run (largest area).
fprintf('The values of the longest run are: ');
valuesOfLongest = measurements(sortIndices(1)).PixelValues;
fprintf('%d ', valuesOfLongest);
fprintf('\n');
In the command window, you'll see the results:
a =
3 10 7 6 2 3 4 8
labeled =
0 1 1 1 0 0 0 2
measurements =
2x1 struct array with fields:
Area
PixelValues
allAreas =
3 1
sortedAreas =
3 1
sortIndices =
1 2
The values of the longest run are: 10 7 6
If you don't follow that, let me know.

类别

Help CenterFile Exchange 中查找有关 Image Data Workflows 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by