How to replace a number in a row vector with NaN in certain condition

조회 수: 1 (최근 30일)
I have raw vector like this
x = [15 13 9 20 12 15 2 25 17 3 2 5 18 4 12 30 32 40 1 19];
What I need is to replace a number with NaN when the following condition happen.
Whenever the abs difference between x(i) and x(i+1) is >10 replace x(i+1) with NaN , and continue next computation between x(i) and x(i+2) by skipping the value that is assigned as ‘NaN’. If the abs diff between x(i) and x(i+2) is <10, Then the next computation has to be between x(i+2) and x(i+3). But if the abs diff between x(i) and x(i+2) was >10, x(i+2) would be replace by ‘Nan” and next computation would be between x(i) and x(i+3).
In similar way computation continue and returned result should be as follow
x_new = [15 13 9 NaN 12 15 NaN NaN 17 NaN NaN NaN 18 NaN 12 NaN NaN NaN NaN 19]

채택된 답변

per isakson
per isakson 2021년 5월 29일
편집: per isakson 2021년 5월 29일
abs(x(6)-x(8)) is equal to 10. Accourding to x_new, x(8) should be replaced by NaN. Thus I have use ">=".
%%
vec = [15 13 9 20 12 15 2 25 17 3 2 5 18 4 12 30 32 40 1 19];
len = numel( vec );
new = vec;
pos = 1;
for jj = 2 : len
if abs(vec(pos)-vec(jj)) >= 10 % Notice ">="
new(jj) = nan;
else
pos = jj;
end
end
%%
x_new = [15 13 9 NaN 12 15 NaN NaN 17 NaN NaN NaN 18 NaN 12 NaN NaN NaN NaN 19];
disp( x_new ), disp( new )
15 13 9 NaN 12 15 NaN NaN 17 NaN NaN NaN 18 NaN 12 NaN NaN NaN NaN 19 15 13 9 NaN 12 15 NaN NaN 17 NaN NaN NaN 18 NaN 12 NaN NaN NaN NaN 19
  댓글 수: 1
Yared Daniel
Yared Daniel 2021년 5월 30일
Thank you so much for understanding my question and solving exactly what I need

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by