如何获取这些数组并使用它们来填充结构的字段?

tee*_*eee 1 arrays matlab struct vector

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

a = [0 5 7]
b = [-2 6 8]
c = 6
d = [11 12 13]
e = 20
Run Code Online (Sandbox Code Playgroud)

我希望结果是

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
Run Code Online (Sandbox Code Playgroud)

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

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

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

Wol*_*fie 5

更新答案

事实证明,您可以利用文档中的这一行:

如果任何值输入是非标量元胞数组,则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) );
Run Code Online (Sandbox Code Playgroud)

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


原答案

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

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, 1, N/numel(x));
% Create the scalar struct with padding
strctA = struct( 'a', pad(a), 'b', pad(b), 'c', pad(c) );
Run Code Online (Sandbox Code Playgroud)

然后你可以有一个循环将其转换为结构数组,它与变量名称没有关系,因此更容易维护:

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
Run Code Online (Sandbox Code Playgroud)