The longest consecutive values in a vector and the position at which it starts and ends
Ältere Kommentare anzeigen
I have a large matrix where I want to find the value that has been repeated the most. Then define its starting and ending indexes. For example
Thanks for the help in advanse!
A = [35, 25, 40, 20, 20, 30, 30, 30, 30, 30, 9, 20, 30, 10, 30]
The solution should be as below
The_Answer = 30
Starting_index = 6;
Ending_index = 10
2 Kommentare
Geoff Hayes
am 13 Okt. 2021
@Yaser Khojah - is this homework? What have you tried so far? What are the dimensions of the large matrix?
Yaser Khojah
am 13 Okt. 2021
Akzeptierte Antwort
Weitere Antworten (2)
Using "Tools for Processing Consecutive Repetitions in Vectors",
A = [35, 25, 40, 20, 20, 30, 30, 30, 30, 30, 9, 20, 30, 10, 30];
[starts,stops,lengths]=groupLims(groupConsec(A),1);
[~,i]=max(lengths);
The_Answer = A(starts(i))
Starting_index = starts(i)
Ending_index = stops(i)
3 Kommentare
Yaser Khojah
am 14 Okt. 2021
Bearbeitet: Yaser Khojah
am 14 Okt. 2021
Matt J
am 14 Okt. 2021
Really? It doesn't look like anyone has downloaded it recently.
Yaser Khojah
am 14 Okt. 2021
Image Analyst
am 14 Okt. 2021
If you have the Image Processing Toolbox (like most people do), you can use bwareafilt() to extract the longest run. Then the code becomes simply:
A = [35, 25, 40, 20, 20, 30, 30, 30, 30, 30, 9, 20, 30, 10, 30]
da = bwareafilt([0, diff(A)] == 0, 1)
startingIndex = max([1, find(da, 1, 'first')-1])
endingIndex = find(da, 1, 'last')
You see
A =
35 25 40 20 20 30 30 30 30 30 9 20 30 10 30
da =
1×15 logical array
0 0 0 0 0 0 1 1 1 1 0 0 0 0 0
startingIndex =
6
endingIndex =
10
Kategorien
Mehr zu Platform and License finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!