简体   繁体   English

数组结构的数组。 MATLAB

[英]Arrays to array of struct. MATLAB

I have three vectors centers, radiuses, metrics all Nx1 ( centers is Nx2, but it is not a problem at all). 我有三个向量centers, radiuses, metrics所有Nx1( centers是Nx2,但它根本不是问题)。 And I want to convert them into vector Nx1 of structures where each structure has fields: center, radius, metric and corresponding values of this fields, like structArray(i).metric == metrics(i) . 我想将它们转换为结构的向量Nx1,其中每个结构都有字段: center, radius, metric和这些字段的相应值,如structArray(i).metric == metrics(i) What is the best and simpliest way to do this? 最好和最简单的方法是什么?

You can use the struct constructor directly by converting you data to cell arrays. 您可以通过将数据转换为单元数组来直接使用struct构造函数。

structArray = struct('center', num2cell(centers,2), ...
                     'radius', num2cell(radiuses), ...
                     'metric', num2cell(metrics));

Note the use of the dimension input to num2cell to convert the centers variable into an Nx1 array of 1x2 cells. 注意使用num2cell的维度输入将centers变量转换为1x2单元格的Nx1数组。

If we try this with some example data: 如果我们尝试使用一些示例数据:

radiuses = rand(3,1);
metrics = rand(3,1);
centers = rand(3,2);

structArray = struct('center', num2cell(centers,2), ...
                     'radius', num2cell(radiuses), ...
                     'metric', num2cell(metrics));

structArray =

3x1 struct array with fields:

    center
    radius
    metric

Use the following: 使用以下内容:

 S = struct( 'centers', num2cell(centers), 'radiuses', num2cell(radiuses), ... 
     'metrics', num2cell(metrics) );

Note, that the overhead (in terms of memory consumption) of this approach is very high. 注意,这种方法的开销(就内存消耗而言)非常高。 If your arrays CENTERS, RADIUSES and METRICS are very large it is better to use the "flat" memory layout, ie to store the arrays in one struct: 如果您的数组CENTERS,RADIUSES和METRICS非常大,最好使用“平面”内存布局,即将数组存储在一个结构中:

S = struct;
S.centers = centers;
S.radiuses = radiuses;
S.metrics == metrics;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM