Extract sub-matrices of matrix between NaN into cell array

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

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?

Sign in to comment.

Answers (2)

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
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));

Products

Asked:

on 13 Feb 2013

Community Treasure Hunt

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

Start Hunting!