Arrays and finding a chain of ones

1 次查看(过去 30 天)
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

类别

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