Clear Filters
Clear Filters

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

2 views (last 30 days)
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

Accepted Answer

Guillaume
Guillaume on 8 Jan 2018
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 Comments
Jose Valles
Jose Valles on 8 Jan 2018
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 on 8 Jan 2018
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)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!