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

2 次查看(过去 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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 NaNs 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by