How can I extract values from a vector element that includes NaN elements?
2 次查看(过去 30 天)
显示 更早的评论
Hi, Let's suppose that we have the following vector
V = [3 4 5 NaN NaN NaN 10 NaN 15 45 95 32 65 NaN NaN]
I would like to extract the numerical values and create new variables from those values.
V1 = [3 4 5]
V2 = [10]
V3 = [15 45 95 32 65]
I think is important to mention that the number of new variables (V1,V2 and V3) should be based on the number of "events" encounter in the vector. In this case 3 "events".
Also, the first vector value can be a number or NaN element
Regards
0 个评论
采纳的回答
Guillaume
2018-1-8
Note that creating numbered variables is an extremely bad idea (search the forum or faq to know why). We'll be creating a cell array that can easily be indexed instead.
Assuming that V does not start by NaN:
V = [3 4 5 NaN NaN NaN 10 NaN 15 45 95 32 65 NaN NaN]; %demo data
grouplength = diff([0 find(diff(isnan(V))) numel(V)]); %find length of non-nan and nan runs
Vgrouped = mat2cell(V, 1, grouplength); %split according to runs
Vgrouped = Vgrouped(1:2:end) %get rid of nan runs, assumes that 1st run is not nan
Your V1, V2, V3 are Vgrouped{1}, Vgrouped{2}, Vgrouped{3} instead. Something that can be easily looped over unlike numbered variables.
2 个评论
Guillaume
2018-1-8
If it starts with NaN you'd start the indexing at 2:
Vgrouped = Vgrouped(2:2:end)
To cater for both cases:
Vgrouped = Vgrouped(1+isnan(V(1)):2:end)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!