How can I extract values from a vector element that includes NaN elements?

조회 수: 3 (최근 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

채택된 답변

Guillaume
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
Jose Valles
Jose Valles 2018년 1월 8일
Thank you for your reply!
You are absolutely correct regarding the numbered variables.
How much it would change the code line if the V variable starts by NaN?
I am telling you this because I want to use this code line in different dataset and sometimes it can start by NaN or not.
Guillaume
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 CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by