如何获取这些数组并将其用于填充结构的字段?

问题描述

我有几个向量,并想用它们来填充结构数组中的字段。向量将永远只有两个长度之一-它们的长度为N或长度为1。例如,如果N = 3,我的向量可能如下所示:

a = [0 5 7]
b = [-2 6 8]
c = 6
d = [11 12 13]
e = 20

我希望结果是

my_structure(1).a = 0
my_structure(2).a = 5
my_structure(3).a = 7

my_structure(1).b = -2
my_structure(2).b = 6
my_structure(3).b = 8

my_structure(1).c = 6
my_structure(2).c = 6
my_structure(3).c = 6

my_structure(1).d = 11
my_structure(2).d = 12
my_structure(3).d = 13

my_structure(1).e = 20
my_structure(2).e = 20
my_structure(3).e = 20

您可以看到,对于最初仅具有length = 1的向量,结构数组的每个元素都应具有相同的值。

是否有一种简洁的方法来实现此目标而不必遍历每个元素?它应该是可扩展的,以便我可以根据需要添加更多向量f,g,h,...。

如注释中所查询,我不能简单地使用my_structure.a = [0 5 7]等,因为我需要能够将my_structure(i)传递给另一个函数,该函数要求每个字段仅包含一个值(不是数组)。

解决方法

更新后的答案

结果是您可以利用文档中的这一行:

如果任何值输入是非标量单元格数组,则s的尺寸与该单元格数组的尺寸相同。

所以

N = 3;          % Each var has 1 or N elements

a = [0 5 7];    
b = [-2 6 8];
c = 6;

% Create an anonymous function to make all vars the correct size CELL (1 or N)
pad = @(x) num2cell( repmat(x,1,N/numel(x)) );
strct = struct( 'a',pad(a),'b',pad(b),'c',pad(c) );

这与下面的原始答案遵循类似的思维模式,但显然更加简洁。


原始答案

最简单的 一个详细的方法是从标量结构开始,然后将其转换为结构数组。所以...

N = 3;          % Each var has 1 or N elements

a = [0 5 7];    
b = [-2 6 8];
c = 6;

% Create an anonymous function to make all vars the correct size (1 or N)
pad = @(x) repmat(x,N/numel(x));
% Create the scalar struct with padding
strctA = struct( 'a',pad(c) );

然后,您可以使用循环将其转换为结构数组,该结构数组与变量名没有关系,因此更易于维护:

f = fieldnames(strctA);  % Get the field names,i.e. the original variable names
strctB = struct([]);     % Create an output struct. The [] input makes it a struct array
for iFn = 1:numel(f)     % Loop over the fields
    for n = 1:N          % Loop over the array elements
        strctB(n).(f{iFn}) = strctA.(f{iFn})(n); % Assign to new structure
    end
end
,

Wolfie的答案确实很聪明,但是您也可以使用一个for循环使用更直接的解决方案:

N = 3;

a = [0 5 7]
b = [-2 6 8]
c = 6
d = [11 12 13]
e = 20

for i = 1:N
    my_structure(i).a = a(min(length(a),i))
    my_structure(i).b = b(min(length(b),i))
    my_structure(i).c = c(min(length(c),i))
    my_structure(i).d = d(min(length(d),i))
    my_structure(i).e = e(min(length(e),i))
end

这种方法的优点是您的代码更易于阅读。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...