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?
0 件のコメント
採用された回答
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 件のコメント
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
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
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Image Data Workflows についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!