Split numeric values of vector with NaN to individual matrices

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

Accepted Answer

madhan ravi
madhan ravi on 26 Jan 2019
Edited: madhan ravi on 26 Jan 2019
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 Comment
puccapearl
puccapearl on 17 Apr 2024 at 0:22
This works great! Could you explain what the code is doing, line by line? Thanks!

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!