How to get the longest consecutive values in a column vector and the position at which it starts

조회 수: 14 (최근 30일)
Hello,
Suppose i have a single column vector A'=[0 0 0 1 0 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1]
I only want the longest consecutive values of 1's and display only that.
I'd really appreciate any help!

채택된 답변

Bruno Luong
Bruno Luong 2019년 8월 24일
편집: Bruno Luong 2019년 8월 24일
A=[0 0 0 1 0 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1]'
i=reshape(find(diff([0;A;0])~=0),2,[]);
[lgtmax,jmax]=max(diff(i));
istart=i(1,jmax);
lgtmax % length of the longest sequence of 1s
istart % where it starts
  댓글 수: 3
Bruno Luong
Bruno Luong 2019년 8월 24일
편집: Bruno Luong 2019년 8월 24일
The terminologies are mine it doesn't matter for MATLAB syntax.
Actually my code is compact but difficult to understand, even for people who are initiated.
If you want to understand, you can split into multiple small and basic commands to analyze it and read the doc of corresponding command and experiment with your own examples.
[0;A;0]
Pad 0s at the header and trailer of A.
The command
diff([0;A;0])~=0
returns a logical array with TRUE whene there is a transitions (0->1) or (1->0).
And the TRUE positions must come in pairs: alternate in order of 0->1, 1->0, 0->, 1->0, etc ... since I take care to pad the arrays with 0s in both ends.
So by reshaping
i=reshape(... ,2,[]);
I'll get two-row array, the first row contains index positions of 0->1, and the second row of 1->0. You'll need to know about MATLAB major-column storage scheme for array to fully understand such trick.
Therefore the difference of the two columns is the the length of the consecutive 1s in A with this command:
diff(i);
By doing
[lgtmax,jmax]=max(diff(i));
I search for the longest sequence of 1s, and the number of this sequence is in retreived in jmax.
The last command
istart=i(1,jmax)
just maps back the starting position of this sequence in A (since I pad 0 in the head, it's actually the position of the first 1).

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

추가 답변 (2개)

Walter Roberson
Walter Roberson 2019년 8월 24일
  댓글 수: 1
Meghana Balasubramanian
Meghana Balasubramanian 2019년 8월 24일
Thank you, but I was looking for a matlab code to help me out rather than a downloadable function, even if it does make my job easier.

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


Benjamin Hezrony
Benjamin Hezrony 2024년 10월 6일

It can also be done in one line:

B = bwareafilt(A,1)

A classic function in segmentation!

https://www.mathworks.com/help/images/ref/bwareafilt.html#d126e42061

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by