How to segment one row matrix into multiple row matrix
3 ビュー (過去 30 日間)
古いコメントを表示
Hi, I do have for example this matrix [ 3 6 4 5 6 NaN 8 9 10 NaN NaN NaN 13 14 5 6 0 1 NaN NaN 2 3 NaN NaN NaN 9 1 5 NaN 2 8 NaN] and i would like to have matrix where each row would be each segment of values.
I mean like:
3 6 4 5 6
8 9 10
13 14 5 6 0 1
2 3
9 1 5
2 8
0 件のコメント
回答 (1 件)
David Fletcher
2021 年 4 月 10 日
Ultimately you can't have a matrix of the segments since they are potentially of different lengths - you could have a cell array of them though. Something like this:
A=[ 3 6 4 5 6 NaN 8 9 10 NaN NaN NaN 13 14 5 6 0 1 NaN NaN 2 3 NaN NaN NaN 9 1 5 NaN 2 8 NaN]
nanLoc=isnan(A);
partial=[];
vecCount=1;
iter=1;
vectors={};
while iter<=numel(A)
if (nanLoc(iter)==1)
if ~isempty(partial)
vectors{vecCount} = partial;
vecCount=vecCount+1
end
partial=[];
else
partial=[partial A(iter)];
end
iter=iter+1;
end
Running it gives
vectors =
1×6 cell array
{[3 6 4 5 6]} {[8 9 10]} {[13 14 5 6 0 1]} {[2 3]} {[9 1 5]} {[2 8]}
2 件のコメント
David Fletcher
2021 年 4 月 10 日
If you wished to pad them to the same length and store them in a matrix, then yes you could do that. However, you (presumably) could not know beforehand what size the segments would need to be padded to - saying that some trivial analysis of the nanLoc vector could give you such a value. Also whatever you used to pad the vectors couldn't be a value that would naturally occur in the vector (or you would have no way of knowing whether a pad value was genuine or naturally occuring). One final thing, as it often the case I have just noticed a problem in the code I've provided - if the original array doesn't end in a NaN, the final partial value will fail to be written to vectors cell array - but then I guess it does leave something for you to do...
参考
カテゴリ
Help Center および File Exchange で NaNs についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!