Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split matrix based on number in first column

Tags:

matrix

matlab

I have a matrix which has the following form:

M = 
[1 4 56 1;
 1 3 5  1;
 1 3 6  4;
 2 3 5  0;
 2 0 0  0;
 3 1 2  3;
 3 3 3  3]

I want to split this matrix based on the number given in the first column. So I want to split the matrix into this:

A = 
[1 4 56 1;
 1 3 5  1;
 1 3 6  4]

B = 
[2 3 5  0;
 2 0 0  0]

C =
[3 1 2  3;
 3 3 3  3]

I tried this by making the following loop, but this gave me the desired matrices with rows of zeros:

for i = 1:length(M)
    if (M(i,1) == 1)
        A(i,:) = M(i,:);
    elseif (M(i,1) == 2)
        B(i,:) = M(i,:);
    elseif (M(i,1) == 3)
        C(i,:) = M(i,:);
    end
end

The result for matrix C is then for example:

C = 
[0 0 0 0;
 0 0 0 0;
 0 0 0 0;
 2 3 5 0;
 2 0 0 0]

How should I solve this issue?

Additional information:
The actual data has a date in the first column in the form yyyymmdd. The data set spans several years and I want to split this dataset in matrices for each year and after that for each month.

like image 834
Saaru Lindestøkke Avatar asked Dec 27 '22 17:12

Saaru Lindestøkke


1 Answers

You can use arrayfun to solve this task:

M = [
1 4 56 1;
 1 3 5  1;
 1 3 6  4;
 2 3 5  0;
 2 0 0  0;
 3 1 2  3;
 3 3 3  3]


A = arrayfun(@(x) M(M(:,1) == x, :), unique(M(:,1)), 'uniformoutput', false)

The result A is a cell array and its contents can be accessed as follows:

>> a{1}

ans =

     1     4    56     1
     1     3     5     1
     1     3     6     4

>> a{2}

ans =

     2     3     5     0
     2     0     0     0

>> a{3}

ans =

     3     1     2     3
     3     3     3     3

To split the data based on an yyyymmdd format in the first column, you can use the following:

yearly = arrayfun(@(x) M(floor(M(:,1)/10000) == x, :), unique(floor(M(:,1)/10000)), 'uniformoutput', false)

monthly = arrayfun(@(x) M(floor(M(:,1)/100) == x, :), unique(floor(M(:,1)/100)), 'uniformoutput', false)
like image 150
H.Muster Avatar answered Jan 05 '23 02:01

H.Muster