parsing a vector by NaN into separte, unequal vectors into a cell array

6 ビュー (過去 30 日間)
Matthew
Matthew 2015 年 3 月 17 日
回答済み: Guillaume 2015 年 3 月 17 日
I'm trying to parse a vector with NaN, into a cell array that is delineated by the start and stop of the NaN
example = [1 2 3 Na Na 2 3 Na 4 5 6 7 Na Na Na Na 1];
and turn that into
answer = {[1 2 3] [2 3] [4 5 6 7] [1]}
any suggestions? I've been using find(isnan(example)) to get the indices of NaN, but what I really need are the stop and stop indices of the non - NaN segments
Thanks!

採用された回答

Sean de Wolski
Sean de Wolski 2015 年 3 月 17 日
編集済み: Sean de Wolski 2015 年 3 月 17 日
EDIT
Here's a fully vectorized engine that keeps original indices. This requires the Image Processing Toolbox.
x = [1 2 3 nan nan 2 3 nan 4 5 6 7 nan nan nan 1];
notnans = ~isnan(x);
idx = bwlabel(notnans);
n = histcounts(idx);
oneToN = 1:numel(x);
C = mat2cell([x(notnans); oneToN(notnans)],2,n(2:end))
  2 件のコメント
Matthew
Matthew 2015 年 3 月 17 日
Thanks! Would there be a way to have the original indices in the answer?:
so that:
answer = {[1 2 3;1 2 3] [6 7; 2 3] [9 10 11 12; 4 5 6 7] [16;1];
Thanks for your help
Sean de Wolski
Sean de Wolski 2015 年 3 月 17 日
See EDIT

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

その他の回答 (1 件)

Guillaume
Guillaume 2015 年 3 月 17 日
Here is a solution that does not require any toolbox:
x = [1 2 3 nan nan 2 3 nan 4 5 6 7 nan nan nan 1];
transitions = diff([1 isnan(x) 1]);
starts = find(transitions == -1);
lengths = find(transitions == 1) - starts;
nonanx = arrayfun(@(s, l) {[s:s+l-1; x(s:s+l-1)]}, starts, lengths)

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by