Search code examples
arraysmatlabcellsdivide

Divide cell or array of arbitrary size into pieces of defined size


I have a list of coordinate data that I am trying to divide into pieces small enough to send to a microcontroller.

Currently I have a cell of data that looks like this which is quite large:

    [46.06,32.98]
    [15.66,78,42]

Etc.

I need to round the values so I convert it to a matrix with cell2mat and use the round function. Then it looks like this where there are two colums:

    46 32
    15 78

Etc.

MATLAB calls this a (nx2) double in the variable window, n being all the coordinate pairs.

I want to split this double array into sections of five rows of coordinates, because my Arduino can only handle so much data at one time. The amount of coordinate pairs is often not a multiple of 5, so I need to fill the rest with null.

I have the rest from there.

    Centroid = {blobSelects.Centroid}.'; %where I create the coordinate cell
    raws = cell2mat(Centroid); %I create the nx2 double
    cleans = round(raws); %I round the values

    %Here I write it to a table
    T = cell2table(cleans,'VariableNames',{'X','Y'}); 

    % and save it on a microSD card.
    dlmwrite('E:\data.txt', 'tabledata.txt', 'delimiter', '\t')    

Solution

  • Try this:

    A = randi([0, 100],randi(50),2); %// replace with your actual matrix
    padSize = ceil(size(A,1)/5)*5 - size(A,1);
    A = vertcat(A,nan(padSize,2));
    
    out1 = mat2cell(A,ones(1,size(A,1)/5)*5,2); %// Desired cell array
    

    If you want it as a 3D matrix (as they all are of same size 5x2), you could use

    out = permute(reshape(A,5,size(A,1)/5,[]),[1 3 2]);