I need to remove separate zeros from a series of numbers. But if zeros repeat, I need to keep them.
example of vector:
A = [ 0 0 1 0 0 0 1 0 1 0 0 1 5 9 8 2 0 3 0 1 0 0 0 ];
result:
A = [ 0 0 1 0 0 0 1 1 0 0 1 5 9 8 2 3 1 0 0 0 ];

 채택된 답변

Rik
Rik 2021년 10월 6일

0 개 추천

It took a bit of thinking, but here is a oneliner:
A = [ 0 0 1 0 0 0 1 0 1 0 0 1 5 9 8 2 0 3 0 1 0 0 0 ];
A(conv([NaN A]==0,[-1 1 -1])==1)=[];
A
A = 1×20
0 0 1 0 0 0 1 0 1 0 1 5 9 8 2 0 3 1 0 0
Thanks to @Alan Stevens for the idea of converting A to a logical and ignoring it for the rest of the processing.

댓글 수: 1

Legally Blonde
Legally Blonde 2021년 10월 6일
Thank you so much for the quick answers! You're great! I will certainly use the answers to other problems in the processing of my meteorological data.

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

추가 답변 (1개)

Alan Stevens
Alan Stevens 2021년 10월 6일

0 개 추천

Here's one way (there is probably a slicker way!):
A = [ 0 0 1 0 0 0 1 0 1 0 0 1 5 9 8 2 0 3 0 1 0 0 0 ];
ix = find(A~=0);
it = find(abs(diff(ix))==2);
remove = ix(it+1)-1;
A(remove)=[]
A = 1×20
0 0 1 0 0 0 1 1 0 0 1 5 9 8 2 3 1 0 0 0

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

질문:

2021년 10월 6일

댓글:

2021년 10월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by