Search code examples
matlabcells

Loop to create cell array


I have a structure named data. The structure has 250 elements and one field called codes (whose dimension varies).

As an example: data(1).codes is a 300 x 1 cell of strings and data(2).codes is a 100 x 1 cell of strings.

What I am trying to do is to create a big cell with three columns: id count codes where id indexes the element number (1 to 250), count indexes the row of the string and codes are just the codes.

An example to make it clear:

for k = 1:size(data,2)
    id  = repmat(k,size(data(k).codes,1),1);
    count = linspace(1, size(data(k).codes,1), size(data(k).codes,1))';
    codes= data(k).codes;   
end

The loop above creates the columns I want. Now I just need to append them one below the other and then save to excel. If these where only numbers I knew how to concatenate/append matrices. But with cells I am unsure how to do it.

Here is what I have tried:

output = {};

for k = 1:size(data,2)
     id  = repmat(k,size(data(k).codes,1),1);
     count = linspace(1, size(data(k).codes,1), size(data(k).codes,1))';
     codes= data(k).codes;   

     output{1,1} = {output{1,1}; id};
     output{1,2} = {output{1,2}; count};
     output{1,3} = {output{1,3}; 
end

Solution

  • Build up your output into a new cell array, allowing for pre-allocation, then concatenate all of your results.

    % Initialise
    output = cell(size(data,2), 1);
    % Create output for each element of data
    for k = 1:size(data,2)
        id  = repmat(k,size(data(k).codes,1),1);
        count = linspace(1, size(data(k).codes,1), size(data(k).codes,1))';
        codes = data(k).codes;   
        % add to output
        output{k} = [id, count, codes];     
    end
    % Vertically concatenate all cell elements
    output = vertcat(output{:});
    

    Note: this assumes codes is numerical, and the output will be a numerical matrix. If it isn't, you will need to do some cell conversions for your numerical data (id and count) like so:

    id = repmat({k}, size(data(k).codes,1), 1);
    count = num2cell(linspace( ... )');