Loop to create cell array

谁说我不能喝 提交于 2021-01-27 18:18:57

问题


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

回答1:


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( ... )');


来源:https://stackoverflow.com/questions/49896868/loop-to-create-cell-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!