How to merge adjacent NaN values into single NaN value in a vector?

1 次查看(过去 30 天)
I have [1 2 3 NaN NaN 0 1 2 NaN 9 8 7 6 NaN NaN NaN 1 1] anf I want [1 2 3 NaN 0 1 2 NaN 9 8 7 6 NaN 1 1] without a for cycle. Are there any trick to do this?

采纳的回答

Stephen23
Stephen23 2018-7-1
编辑:Stephen23 2018-7-3
No loops required, no tricks required, just basic MATLAB indexing:
old = [1 2 3 NaN NaN 0 1 2 NaN 9 8 7 6 NaN NaN NaN 1 1];
idx = ~isnan(old);
new = old(idx | [true,idx(1:end-1)]);
  3 个评论
Stephen23
Stephen23 2018-7-3
编辑:Stephen23 2018-7-3
@Mr M.: you are right. It is easy to fix, just exchange the false for true:
>> old = [NaN,NaN,NaN,1,2,3,NaN,NaN,0,1,2,NaN,9,8,7,6,NaN,NaN,NaN]
old =
NaN NaN NaN 1 2 3 NaN NaN 0 1 2 NaN 9 8 7 6 NaN NaN NaN
>> idx = ~isnan(old);
>> new = old(idx | [true,idx(1:end-1)])
new =
NaN 1 2 3 NaN 0 1 2 NaN 9 8 7 6 NaN

请先登录,再进行评论。

更多回答(1 个)

Andrei Bobrov
Andrei Bobrov 2018-7-2
a = [1 2 3 NaN NaN 0 1 2 NaN 9 8 7 6 NaN NaN NaN 1 1];
lo = ~isnan(a);
lo(strfind(lo,[0 1])) = true;
out = a(lo);

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by