find first& end of array

2 visualizaciones (últimos 30 días)
주희 박
주희 박 el 20 de Mayo de 2022
Respondida: Stephen23 el 20 de Mayo de 2022
Hi
S=[ 0 1 5 2 0 0 0 9 3 50 53 0 0 5 7 4] ;
And I want to pick first&last number of continued numbers except 0.
Like in S ->1 ,2 ,9,53, 5,4
Are there any good method?
Thank you.

Respuesta aceptada

Stephen23
Stephen23 el 20 de Mayo de 2022
S = [0,1,5,2,0,0,0,9,3,50,53,0,0,5,7,4]
S = 1×16
0 1 5 2 0 0 0 9 3 50 53 0 0 5 7 4
X = diff([0;S(:)]==0)<0 | diff([S(:);0]==0)>0;
V = S(X)
V = 1×6
1 2 9 53 5 4

Más respuestas (2)

the cyclist
the cyclist el 20 de Mayo de 2022
I expect someone will post a more elegant method, but I think this does what you want
S=[0 1 5 2 0 0 0 9 3 50 53 0 0 5 7 4];
first = S(diff([0 S]) == S & S~=0);
last = S(diff([S 0]) ==-S & S~=0);
firstLast = [first; last];
output = firstLast(:)'
output = 1×6
1 2 9 53 5 4

Image Analyst
Image Analyst el 20 de Mayo de 2022
Here's a different way:
S=[0 1 5 2 0 0 0 9 3 50 53 0 0 5 7 4];
S2 = [0,S,0];
indexes = sort([strfind(S2~=0, [0 1]) + 1, strfind(S2~=0, [1,0])])
indexes = 1×6
3 5 9 12 15 17
S3 = S2(indexes)
S3 = 1×6
1 2 9 53 5 4

Categorías

Más información sobre Programming en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by