Split numeric values of vector with NaN to individual matrices

17 ビュー (過去 30 日間)
Konstantinos Tsitsilonis
Konstantinos Tsitsilonis 2019 年 1 月 26 日
コメント済み: puccapearl 2024 年 4 月 17 日
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 日
This works great! Could you explain what the code is doing, line by line? Thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by