3

I have in a matrix data that contains 0 and 'proper' data. I want to crete several matrixes (new ones) to separate the data from the zeros and get rid of these zeros.

So, here is a simple example:

data = 1   3   6   4
       3   6   9   5
       4   5   6   2
       0   0   0   0
       0   0   0   0
       2   4   1   8
       1   4   6   5
       0   0   0   0
       1   7   9   1
       3   4   5   8

And i want to get in this case two matrixes that would be:

A =1   3   6   4
   3   6   9   5
   4   5   6   2



B= 2   4   1   8
   1   4   6   5



C = 1   7   9   1
    3   4   5   8

Obviously my data files have thousands of datapoint and i need to automat this.

Any ideas how to do it?

tmpearce
  • 12,523
  • 4
  • 42
  • 60
Flowers
  • 59
  • 1
  • 2
  • 12

2 Answers2

4

Step 1: create an index of the rows containing only zeros using all:

index = all(data==0,2); #% data==0<-- logical matrix; the 2 means along dimension 2

Step 2: create vectors containing the first and last indices of each segment of desired values:

index = [1; double(index); 1]; #% convert to numeric and pad with ones
firsts = diff(index)==-1; #% 0 (real row) - 1 (spacer row) = -1
lasts = (diff(index)==1)-1; #% subtract 1 because of padding

Step 3: Create a cell array which contains sequential segments of the original matrix in each cell (using cell arrays, each cell can be a different size, or even a different type):

#% firsts and lasts should be the same length
#% iterate through lists of first/last indices
for ii=1:length(firsts)
    result{ii} = data(firsts(ii):lasts(ii), :);
end

Obligatory Matlab public service announcement: i and j are popular loop index variables... you'll notice I used ii instead. Here's why.

Community
  • 1
  • 1
tmpearce
  • 12,523
  • 4
  • 42
  • 60
2

here's an alternative way that keeps the # of columns of data in the resulted cell array:

   L=bwlabel(data);
   for n=1:max(L)
       result{n}=reshape(data(L==n),[],size(data,2));
   end


result = 
[3x4 double]    [2x4 double]    [2x4 double]

result{1}
ans =
         1     3     6     4
         3     6     9     5
         4     5     6     2
bla
  • 25,846
  • 10
  • 70
  • 101