Arrays and finding a chain of ones

4 vues (au cours des 30 derniers jours)
Rasmus
Rasmus le 13 Avr 2014
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?

Réponse acceptée

Azzi Abdelmalek
Azzi Abdelmalek le 13 Avr 2014
Modifié(e) : Azzi Abdelmalek le 13 Avr 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 commentaires
Rasmus
Rasmus le 13 Avr 2014
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 le 13 Avr 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.

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 13 Avr 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

Community Treasure Hunt

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

Start Hunting!

Translated by