How can I extract values from a vector element that includes NaN elements?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Guillaume
le 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 commentaires
Guillaume
le 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)
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Performance and Memory dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!