Search code examples
matlabmatrixindexingcell-array

How to rearrange cell contents into a single matrix in Matlab


Let's say I have a cell called data with three elements. Each cell element contains an (n x 2) matrix. The first column of each cell in data is the ID of the data next to it, while the second column is the actual data. Note that the actual data I'm working with doesn't consist of rand numbers, but are actual specific numbers.

data = cell(1,3);

data{1} = [1 rand ;
           2 rand ;
           3 rand ;
           4 rand];

data{2} = [2 rand ;
           3 rand ;
           4 rand ;
           5 rand ;
           6 rand];

data{3} = [2 rand ;
           5 rand ;
           6 rand ;
           7 rand ;
           8 rand ;
           9 rand];

I want to rearrange the contents of data into a matrix called rearrange as shown below. As you can see, ID 1 only exists in data{1}, so rand is considered to be zero in the third and fourth column of the first row in rearrange. As you can see, ID 9 only exists in data{3}, so rand is considered to be zero in the second and third column of the ninth row in rearrange.

rearrange = [1 rand 0    0    ; 
             2 rand rand rand ;
             3 rand rand 0    ;
             4 rand rand 0    ;
             5 rand rand rand ;
             6 0    rand rand ;
             7 0    0    0    ;
             8 0    0    rand ;
             9 0    0    rand];

In this case the unique IDs are 1:9 but I want to automate the list of unique IDs rather than just saying 1:9.


Solution

  • This can be done using a for loop pretty easily:

    CellData = data; 
    for n = 1:length(CellData) %loop through each cell
        indices = CellData{n}(:,1); %extract indices
        values = CellData{n}(:,2); % extract values
        Matrix(indices, n) = values; %assign values to correct location
    end
    % add the first column in
    sMatrix = size(Matrix);
    counter = 1:sMatrix(1);
    finalMatrix = [counter' Matrix];