循环创建单元格数组 [英] Loop to create cell array

查看:65
本文介绍了循环创建单元格数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 data 的结构.该结构包含250个元素和一个称为 codes 的字段(其尺寸各不相同).

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

例如: data(1).codes 是一个 300 x 1 字符串单元格,而 data(2).codes 是一个 100 x 1 字符串单元格.

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.

我想做的是创建一个具有三列的大单元格: id计数代码其中 id 索引元素编号(1到250), count 索引字符串的行,而 codes 只是代码.

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.

一个清楚的例子:

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

上面的循环创建我想要的列.现在,我只需要将它们一个附加在另一个下面,然后保存为excel.如果只有这些,我知道如何连接/附加矩阵.但是对于细胞,我不确定该怎么做.

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.

这是我尝试过的:

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

推荐答案

将您的输出构建到新的单元格数组中,以便进行预分配,然后将所有结果串联起来.

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{:});

注意:这假定 codes 是数字,并且输出将是数字矩阵.如果不是,您将需要对数字数据( id count )进行一些单元格转换,如下所示:

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

这篇关于循环创建单元格数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆