MATLAB Answers

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

15 views (last 30 days)
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!


Sign in to comment.

Accepted Answer

Bruno Luong
Bruno Luong on 24 Aug 2019
Edited: Bruno Luong on 24 Aug 2019
A=[0 0 0 1 0 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1]'
lgtmax % length of the longest sequence of 1s
istart % where it starts


Meghana Balasubramanian
Meghana Balasubramanian on 24 Aug 2019
This helps!
But as an amateur who just started learning matlab, it's quite difficult to understand the terminologies: lgtmax and jmax. I was unable to find the theory behind this. Could you please explain how this works?
Thank you
Bruno Luong
Bruno Luong on 24 Aug 2019
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.
Pad 0s at the header and trailer of A.
The command
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:
By doing
I search for the longest sequence of 1s, and the number of this sequence is in retreived in jmax.
The last command
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).

Sign in to comment.

Translated by