Deleting Rows inbetween NaN values.

5 ビュー (過去 30 日間)
Chad
Chad 2020 年 4 月 14 日
編集済み: Stephen23 2020 年 4 月 23 日
I got a row vector that looks like this: V = [ 1 4 5 NaN 0 9 3 1 3 NaN 1 5 3 0 7 NaN 7 4 2 1 NaN 9 4 ]. I want to delete all the columns in between the NaN values, and place the remaining columns in a cell array, it will look like this: Output = { [ 1 4 5 ] [ 1 5 3 0 7 ] [ 9 4 ] }. Not all the vectors in the array will be the same length, so a simple reshape will not work. There are thousands of lines as well. Thank You.
  2 件のコメント
Peng Li
Peng Li 2020 年 4 月 14 日
It wasn't quite clear that the [1 5 3 0 7] subset is also in between two NaN values, while you keep it?
Chad
Chad 2020 年 4 月 14 日
Yes, I want every other subset between the NaN values to be kept, starting with the first one, as the cell array Output suggest.

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

回答 (2 件)

Stephen23
Stephen23 2020 年 4 月 23 日
編集済み: Stephen23 2020 年 4 月 23 日
>> V = [1,4,5,NaN,0,9,3,1,3,NaN,1,5,3,0,7,NaN,7,4,2,1,NaN,9,4];
>> X = isnan(V);
>> Y = cumsum(X);
>> F = @(n) V(~X&(n==Y));
>> C = arrayfun(F, 0:2:max(Y), 'UniformOutput',false);
>> C{:}
ans =
1 4 5
ans =
1 5 3 0 7
ans =
9 4

Vinai Datta Thatiparthi
Vinai Datta Thatiparthi 2020 年 4 月 23 日
Hi Chad,
Understanding the problem from the single example that you mentioned, this following approach was one of the simplest that I could think of -
v = [ 1 4 5 NaN 0 9 3 1 3 NaN 1 5 3 0 7 NaN 7 4 2 1 NaN 9 4 ]; % Input array
idN = isnan(v); % For NaNs in array
idF = find(idN == 1); % Find indices of NaNs
out = {}; % Output cell array
for i = 1:2:numel(idF)
if i == 1
out{end+1} = v(1:idF(1)-1); % For first index
else
out{end+1} = v(idF(i-1)+1:idF(i)-1); % For the rest
end
end
if rem(numel(idF),2) == 0
out{end+1} = v(idF(end)+1:end); % At the end
end
Hope this helps!

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by