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
댓글 수: 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에서 Performance and Memory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!