Extract sub-matrices of matrix between NaN into cell array
Show older comments
Say I have a matrix of values
A=
[NaN,NaN;
NaN,NaN;
NaN,NaN;
-12,14;
-13,14;
-14,13;
-15,13;
NaN,NaN;
NaN,NaN;
NaN,NaN;
NaN,NaN;
NaN,NaN;
-15,13;
-14,13;
-13,14;
-12,14;
-12,13;
-11,13;
-10,14;
-9,14;
NaN,NaN;
NaN,NaN;
NaN,NaN;
NaN,NaN]
How can I extract the segments of the matrix that are between NaN into a cell array where each cell is an extracted matrix?
EDIT Say instead I have matrix as such: B2= [NaN,NaN;NaN,NaN;NaN,NaN;-12,14;-13,14;-14,13;-15,13;NaN,NaN;NaN,NaN;... NaN,NaN;NaN,NaN;NaN,NaN;-15,13;-14,13;-13,14;-12,14;-12,13;-11,13;... -10,14;-9,14;NaN,NaN;NaN,NaN;NaN,NaN;NaN,NaN;-11,12;-13,13;NaN,NaN];
B2 =
NaN NaN
NaN NaN
NaN NaN
-12 14
-13 14
-14 13
-15 13
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
-15 13
-14 13
-13 14
-12 14
-12 13
-11 13
-10 14
-9 14
NaN NaN
NaN NaN
NaN NaN
NaN NaN
-11 12
-13 13
NaN NaN
NaN NaN
How do I extract each non-NaN part into a separate cell of a cell array? The number of NaNs vary as does the length of the non-NaNs sections. NaNs will always be paired between columns. Pedro Villena presented a solution that works when the length of the non-NaN part gets sequential larger but this is not the case in the actual data or in the variable B2 above. I will be doing this multiple times on matrices much longer 78000-350000 rows x 4-6 columns.
1 Comment
Doug Hull
on 13 Feb 2013
you need to be more specific. Are you doing this once, for this specific matrix? Will NaN always be paired like this. Will there always be non-NaN, will there always be two blocks, or N-blocks?
Answers (2)
Jan
on 14 Feb 2013
A = [NaN,NaN;NaN,NaN;NaN,NaN;-12,14;-13,14;-14,13;-15,13;NaN,NaN;NaN,NaN;...
NaN,NaN;NaN,NaN;NaN,NaN;-15,13;-14,13;-13,14;-12,14;-12,13;-11,13;...
-10,14;-9,14;NaN,NaN;NaN,NaN;NaN,NaN;NaN,NaN;-11,12;-13,13;NaN,NaN];
pos = [true, isnan(A(:, 1)).', true];
ini = strfind(pos, [true, false]);
fin = strfind(pos, [false, true]) - 1;
C = cell(1, length(ini));
for iC = 1:length(ini)
C{iC} = A(ini(iC):fin(iC), :);
end
Andrei Bobrov
on 14 Feb 2013
Edited: Andrei Bobrov
on 15 Feb 2013
i1 = all(~isnan(A),2);
i2 = i1(:)';
idx = [strfind([~i2(1),i2],[0 1]); strfind([i2, ~i2(end)],[1 0])];
B = mat2cell(A(i1,:),diff(idx)+1,size(A,2));
Categories
Find more on Descriptive Statistics in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!