Arrays and finding a chain of ones

조회 수: 2 (최근 30일)
Rasmus
Rasmus 2014년 4월 13일
답변: Image Analyst 2014년 4월 13일
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?

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2014년 4월 13일
편집: Azzi Abdelmalek 2014년 4월 13일
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
Rasmus
Rasmus 2014년 4월 13일
it seems like this code looks for a chain with a defined max length? but what if i don't want to define a length, and just want to find the longest chain, without knowing how long it is?
Image Analyst
Image Analyst 2014년 4월 13일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2014년 4월 13일
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

Community Treasure Hunt

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

Start Hunting!

Translated by