Split numeric values of vector with NaN to individual matrices
16 views (last 30 days)
Show older comments
Konstantinos Tsitsilonis
on 26 Jan 2019
Commented: puccapearl
on 17 Apr 2024
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
0 Comments
Accepted Answer
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
on 17 Apr 2024
This works great! Could you explain what the code is doing, line by line? Thanks!
More Answers (0)
See Also
Categories
Find more on Numeric Types in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!