Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new matrix from existing matrix between zeros

Tags:

matrix

matlab

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?

like image 940
Flowers Avatar asked Dec 09 '25 10:12

Flowers


1 Answers

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.

like image 131
tmpearce Avatar answered Dec 12 '25 02:12

tmpearce