Split numeric values of vector with NaN to individual matrices
16 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Konstantinos Tsitsilonis
el 26 de En. de 2019
Comentada: puccapearl
el 17 de Abr. de 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 comentarios
Respuesta aceptada
madhan ravi
el 26 de En. de 2019
Editada: madhan ravi
el 26 de En. de 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 comentario
puccapearl
el 17 de Abr. de 2024
This works great! Could you explain what the code is doing, line by line? Thanks!
Más respuestas (0)
Ver también
Categorías
Más información sobre Numeric Types en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!