gpt4 book ai didi

arrays - 如何在 Matlab 中向结构数组添加新元素?

转载 作者:太空宇宙 更新时间:2023-11-03 19:41:58 25 4
gpt4 key购买 nike

如何向结构数组添加新元素?我无法连接空结构:

>> a=struct;
>> a.f1='hi'

a =

f1: 'hi'

>> a.f2='bye'

a =

f1: 'hi'
f2: 'bye'

>> a=cat(1,a,struct)
Error using cat
Number of fields in structure arrays being concatenated do not match. Concatenation of structure arrays requires that these arrays have the same set of
fields.

那么是否可以添加带有空字段的新元素?

更新

我发现如果同时添加新字段我可以添加新元素:

>> a=struct()

a =

struct with no fields.

>> a.f1='hi';
>> a.f2='bye';
>> a(end+1).iamexist=true

a =

1x2 struct array with fields:

f1
f2
iamexist

没有直路真是不可思议!结构可能有一些冒号等价物?

最佳答案

如果您懒得再次输入字段或者字段太多,那么这里有一个获取空字段结构的捷径

a.f1='hi'
a.f2='bye'

%assuming there is not yet a variable called EmptyStruct
EmptyStruct(2) = a;
EmptyStruct = EmptyStruct(1);

现在 EmptyStruct 是您想要的空结构。所以要添加新的

a(2) = EmptyStruct; %or cat(1, a, EmptyStruct) or [a, EmptyStruct] etc...



a(2)

ans =

f1: []
f2: []

关于arrays - 如何在 Matlab 中向结构数组添加新元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17805291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com