0
votes

I have two matrices X (122 x 125973) and Y (1 x 125973). I want to split in the same way X and Y into smaller matrices and vectors of 122 x 1024 (column division) in Matlab.

I have tried several methods (mat2cell, loops, etc), but I think I am missing the syntax. Any help ?

Note: 125973 can't be divided by 1024, so the last matrix (and vector) will the have the size of (122 x 21) (and (1 x 21) respectively). Thank you for your help!

1
Do you want to store those matrices, or do you want to process them just in time, i.e. is it necessary to have ALL sub-matrices at the same time?HansHirse
Actually I want to use mini-batch for neural network, so I need to store the sub-matrices somewhere.user8751092

1 Answers

1
votes

Since your sub-matrices do not have equal size, you cannot put them in a 3D array (without NaN or zero padding). So you can use a cell. To do this with mat2cell you have to specify how many rows of the original matrix should be put in each individual entry of the cell:

X = rand(122,125973);
Y = rand(1,125973);

% your number of rows per 'block'
n = 1024;

% the number of cols per cell entry: 
colDist = [repelem(n, floor(size(X,2)/n)) rem(size(X,2),n)];
Xcell = mat2cell(X, size(X,1), colDist);
Ycell = mat2cell(Y, size(Y,1), colDist);

Here repelem(n, floor(size(X,2)/n)) repeats n for the number of times n fits in the number of columns of X. Then I append the remainder for the number of columns at the end (rem(size(X,2),n)) of this division to this row vector colDist.

When calling mat2cell (mat2cell(X, rowDist, colDist)) the second argument rowDist should then contain the number of rows per cell entry, which for each cell entry will be equal to the number of rows in X or Y.


Alternatively, you can use a loop to divide the matrix and vector in sub-matrices and put them in the appropriate cell.

Xcell = cell(ceil(size(X,2)/n),1);
Ycell = cell(ceil(size(X,2)/n),1);

% put in the blocks of n rows
for k = 1:floor(size(X,2)/n)
    indices = n*(k-1)+1:n*k;
    Xcell{k} = X(:,indices);
    Ycell{k} = Y(:,indices);
end

% and the remainder:
Xcell{end} = X(:, indices(end)+1:end);
Ycell{end} = Y(:, indices(end)+1:end);