Arrays and finding a chain of ones
1 view (last 30 days)
Show older comments
Okay I have an array which gives me 566 ones and zeros in total. The code i am using is the following.
x0=[zeros(1,276) ones(1,290)];
x0(randperm(566));
So what i need to figure out is how to find the longest chain of ones in this array. Any who has a good solution for this?
0 Comments
Accepted Answer
Azzi Abdelmalek
on 13 Apr 2014
Edited: Azzi Abdelmalek
on 13 Apr 2014
x0=[1 1 1 0 0 1 0 1 1 1 1 1 0 0 1]
x=[0 x0 0]
idx1=strfind(x,[1 0])-1
idx0=strfind(x,[0 1])
[max_length,ii]=max(idx1-idx0+1)
index1=idx0(ii) % The chain containing max_length ones begins at index1
3 Comments
Image Analyst
on 13 Apr 2014
Almost didn't read this because I saw it was accepted but it looked like a trivial thing to do with the Image Processing Toolbox. It's like 3 lines of code. Let me know if you want to see it.
More Answers (1)
Image Analyst
on 13 Apr 2014
Well, for the benefit of anyone who does have the Image Processing Toolbox and wants to know how to find the starting and ending indexes of the longest stretch of "1"s in the array, here is the code:
% Create sample data
x0 = [1 1 0 0 0 1 0 1 1 1 1 1 1 0 0 1 0 1 1 1 0]
% Make measurements of lengths of connected "1" regions.
measurements = regionprops(logical(x0), 'Area', 'PixelIdxList');
% Sort them to find the longest one.
[sortedAreas, sortIndexes] = sort([measurements.Area], 'Descend')
% Get the starting and ending indexes of the largest one.
startingIndex = measurements(sortIndexes(1)).PixelIdxList(1)
endingIndex = measurements(sortIndexes(1)).PixelIdxList(end)
In the command window:
x0 =
1 1 0 0 0 1 0 1 1 1 1 1 1 0 0 1 0 1 1 1 0
sortedAreas =
6 3 2 1 1
sortIndexes =
3 5 1 2 4
startingIndex =
8
endingIndex =
13
0 Comments
See Also
Categories
Find more on Image Data Workflows 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!