Help with removing duplicate sub-elements....

Hi, I have a vector a1 and want to get an output a2. Basically, i should identify the starting index of numbers, keep the first value and replace the repeating elements as NaN. I have no idea how to start since i am new to Matlab. Can someone please help?
a1=[-2 -2 -2 -2 NaN NaN NaN -3 -3 -3 -3 NaN NaN -2 -2 -2 NaN -3 -3 NaN NaN 1 1 1 1 NaN NaN 4 4 4 NaN NaN 3 3 3 NaN];
a2=[-2 NaN NaN NaN NaN NaN NaN -3 NaN NaN NaN NaN NaN -2 NaN NaN NaN -3 NaN NaN NaN 1 NaN NaN NaN 4 NaN NaN NaN NaN 3 NaN NaN NaN];

 채택된 답변

Stephen23
Stephen23 2016년 2월 6일
편집: Stephen23 2016년 2월 6일

0 개 추천

Use isnan and diff to create some indices, then replace those values:
>> A = [-2 -2 -2 -2 NaN NaN NaN -3 -3 -3 -3 NaN NaN -2 -2 -2 NaN -3 -3 NaN NaN 1 1 1 1 NaN NaN 4 4 4 NaN NaN 3 3 3 NaN]
A =
-2 -2 -2 -2 NaN NaN NaN -3 -3 -3 -3 NaN NaN -2 -2 -2 NaN -3 -3 NaN NaN 1 1 1 1 NaN NaN 4 4 4 NaN NaN 3 3 3 NaN
>> B = A;
>> B(-1<diff(isnan([NaN,A]))) = NaN
B =
-2 NaN NaN NaN NaN NaN NaN -3 NaN NaN NaN NaN NaN -2 NaN NaN NaN -3 NaN NaN NaN 1 NaN NaN NaN NaN NaN 4 NaN NaN NaN NaN 3 NaN NaN NaN

댓글 수: 3

Sowmya MR
Sowmya MR 2016년 2월 6일
Thanks Stephen. Can you please generalize this code if the array contains elements between -5 and 4? For example, a1 contains -5 -4 -3 ... so on till 4
Stephen23
Stephen23 2016년 2월 6일
편집: Stephen23 2016년 2월 6일
@Sowmya MR: My code only depends on the NaN's, not the other values. Try it.
Sowmya MR
Sowmya MR 2016년 2월 6일
Awesome. Thank you. Works like a gem

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

추가 답변 (0개)

카테고리

질문:

2016년 2월 6일

댓글:

2016년 2월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by