什么时候在Matlab中使用单元格数组与结构符合是否合适?

CJS*_*CJS 18 arrays matlab struct cell

如果我想在一个变量中存储一些不同大小的字符串或矩阵,我可以考虑两个选项:我可以创建一个struct数组,并让其中一个字段保存数据,

structArray(structIndex).structField
Run Code Online (Sandbox Code Playgroud)

或者我可以使用单元格数组,

cellArray{cellIndex}
Run Code Online (Sandbox Code Playgroud)

但是,何时使用哪种数据结构有一般的经验法则?我想知道在某些情况下使用其中一种是否有缺点.

yuk*_*yuk 16

在我看来,这更多的是方便和代码清晰度.问问自己,您希望通过数字或名称来引用您的变量元素.然后在前一种情况下使用单元数组,在后面使用struct数组.把它想象成你有一个带有和没有标题的表.

顺便说一句,您可以使用CELL2STRUCTSTRUCT2CELL函数轻松地在结构和单元格之间进行转换.

  • 对于单元阵列,您需要一些元数据才能识别单元格内容.精心挑选的字段名称可以让您的代码自我解释. (4认同)

Jon*_*nas 10

如果你在一个函数中使用它进行计算,我建议你使用单元格数组,因为它们更方便处理,这要归功于CELLFUN.

但是,如果您使用它来存储数据(并返回输出),最好返回结构,因为字段名称(应该是)自我记录,因此您不需要记住第7列中的信息.你的细胞阵列.此外,您可以在结构中轻松添加字段"帮助",如果需要,您可以在其中添加字段的其他说明.

结构对于数据存储也很有用,因为如果您想在以后更新代码,可以将它们替换为对象而无需更改代码(至少在您预先分配了结构的情况下).它们具有相同的sytax,但是对象将允许您添加更多功能,例如依赖属性(即基于其他属性即时计算的属性).

最后,请注意,单元格和结构会为每个字段添加几个字节的开销.因此,如果您想使用它们来处理大量数据,那么最好使用包含数组的结构/单元格,而不是使用大型结构/单元数组,其中字段/元素只包含标量.


aba*_*ter 6

此代码表明,单元格数组的大小可能是分配和检索结构的两倍.我没有把这两个操作分开.人们可以很容易地修改代码来做到这一点.

之后运行"whos"表明他们使用非常相似的内存量.

我的目标是用python术语制作一个"列表列表".也许是一个"阵列阵列".

我希望这很有趣/有用!

%%%%%%%%%%%%%%  StructVsCell.m %%%%%%%%%%%%%%%

clear all

M = 100; % number of repetitions
N = 2^10; % size of cell array and struct


for m = 1:M
    % Fill up a template cell array with
    % lists of randomly sized matrices with
    % random elements.
    template{N} = 0;
    for n = 1:N
        r1 = round(24*rand());
        r2 = round(24*rand());
        r3 = rand(round(r2*rand),round(r1*rand()));
        template{N} = r3;
    end

    % Make a cell array equivalent
    % to the template.
    cell_array = template;

    % Create a struct with the
    % same data.
    structure = struct('data',0);
    for n = 1:N
        structure(n).data = template{n};
    end

    % Time cell array
    tic;
    for n = 1:N
        data = cell_array{n};
        cell_array{n} = data';
    end
    cell_time(m) = toc;

    % Time struct
    tic;
    for n = 1:N
        data = structure(n).data;
        structure(n).data = data';
    end
    struct_time(m) = toc;
end

str = sprintf('cell array: %0.4f',mean(cell_time));
disp(str);
str = sprintf('struct: %0.4f',mean(struct_time));
disp(str);
str = sprintf('struct_time / cell_time: %0.4f',mean(struct_time)/mean(cell_time));
disp(str);

% Check memory use
whos

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Run Code Online (Sandbox Code Playgroud)