Insert NaNs (or any value) in several position of a vector

조회 수: 11 (최근 30일)
Luca Amerio
Luca Amerio 2015년 9월 11일
답변: Juliana Damaceno 2019년 1월 23일
Hi i have a vector like this
a=[1 2 3 5 6 7 9 10 13 14];
I would like to find where the diff is bigger than a value (let's say one) and insert a NaN between the two positions. I need this to plot a discontinuous line that is interrupted if the X value grows too much.
I tried something like
ind=diff(a)>1
for i=1:length(a)
if ind(i)
a=[a(1:i),NaN,a(i+1:end)]
end
end
the problem is that whenever I add a NaN the followig value of a get shifted by one positiona and the positions in ind are no longer valid. I could shift ind too or I could copy each value of a into b adding NaN etc etc...
But they all seems over complicated method. Anyone got a good idea on how to do it?
thanks

채택된 답변

the cyclist
the cyclist 2015년 9월 11일
Here is one way:
a=[1 2 3 5 6 7 9 10 13 14];
insertNanIndex = [0 diff(a)>1];
insertValue = (1-insertNanIndex)./0;
b_tmp = [a; insertValue];
b = b_tmp(:)';
b(isinf(b)) = [];
Notice that I temporarily fill in "Inf", and then extract it. So, if your original dataset has "Inf" in it, you will need to do a different dummy var.
  댓글 수: 1
Luca Amerio
Luca Amerio 2015년 9월 11일
SMART!
I have to correct the row
b_tmp = [insertValue; a];
otherwise it insert the NaNs in the wrong position. But...WOW! Nice way to do it!

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

추가 답변 (1개)

Juliana Damaceno
Juliana Damaceno 2019년 1월 23일
If the jump is one followed by the other this way do not work :(

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by