Split numeric values of vector with NaN to individual matrices

조회 수: 38 (최근 30일)
Konstantinos Tsitsilonis
Konstantinos Tsitsilonis 2019년 1월 26일
댓글: puccapearl 2024년 4월 17일 0:22
Hi all,
I have the following vector:
M = [ 1 ; 2 ; 4 ; 4 ; 2 ; Nan ; NaN ; NaN ; 2 ; 4 ; 2 ; 1 ; NaN ; 2 ; 3 ; 2 ; NaN ; NaN] ;
In words, it is a vector with numbers, and consecutive rows of NaN.
I would like to know if there is a function or a quicker way that splits the above vector in to discrete vectors inclusive of only the numeric values, leaving out the NaNs. In the case of the above vector, it could be a cell array for example, such that:
C = [{1 ; 2 ; 4 ; 4 ; 2} ; {2 ; 4 ; 2 ; 1} ; {2 ; 3 ; 2} ] ;
I have managed to make the above happen using indexing but its quite an inefficient method (15lines of code) and it doesn't perform always as expected.
Any Ideas?
KR,
KMT

채택된 답변

madhan ravi
madhan ravi 2019년 1월 26일
편집: madhan ravi 2019년 1월 26일
Note: In your question the first NaN should be NaN not Nan because NaN is valid in Matlab.
M = [ 1 ; 2 ; 4 ; 4 ; 2 ; NaN ; NaN ; NaN ; 2 ; 4 ; 2 ; 1 ; NaN ; 2 ; 3 ; 2 ; NaN ; NaN] ;
index=find(~isnan(M));
idx=find(diff(index)~=1);
A=[idx(1);diff(idx);numel(index)-idx(end)];
C=mat2cell(M(~isnan(M)),A,1);
celldisp(C)
Gives:
C{1} =
1
2
4
4
2
C{2} =
2
4
2
1
C{3} =
2
3
2
  댓글 수: 1
puccapearl
puccapearl 2024년 4월 17일 0:22
This works great! Could you explain what the code is doing, line by line? Thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by