我正在尝试将一个数据点添加到现有的数据结构中。我已经创建了以下数据结构。
ourdata.animal= {'wolf', 'dog', 'cat'}
ourdata.height = [110 51 32]
ourdata.weight = [55 22 10]假设我想要向数据结构中添加另一个名称为'fish' height 3和weight 1的对象,该如何操作?
发布于 2021-09-08 10:05:52
您可以简单地将其附加到结构的末尾:
ourdata.animal{end+1} = 'fish'
ourdata.height(end+1) = 3
ourdata.weight(end+1) = 1发布于 2021-09-18 15:40:35
如果您想处理多个结构,可以编写一个小函数来组合多个结构中的字段的值。下面是一个示例,使用fieldnames()发现存在哪些字段:
function out = slapItOn(aStruct, anotherStruct)
% Slap more data on to the end of fields of a struct
out = aStruct;
for fld = string(fieldnames(aStruct))'
out.(fld) = [aStruct.(fld) anotherStruct.(fld)];
end
end其工作原理如下:
>> ourdata
ourdata =
struct with fields:
animal: {'wolf' 'dog' 'cat'}
height: [110 51 32]
weight: [55 22 10]
>> newdata = slapItOn(ourdata, struct('animal',{{'bobcat'}}, 'height',420, 'weight',69))
newdata =
struct with fields:
animal: {'wolf' 'dog' 'cat' 'bobcat'}
height: [110 51 32 420]
weight: [55 22 10 69]
>> 顺便说一句,我建议你使用string数组而不是data来存储字符串数据。它们在几乎所有方面都更好(除了性能)。使用双引号获取它们:
>> strs = ["wolf" "dog" "cat"]
strs =
1×3 string array
"wolf" "dog" "cat"
>> 另外,对于类似于表格的数据,可以考虑使用table数组而不是结构数组。桌子很不错!
>> animal = ["wolf" "dog" "cat"]';
>> height = [110 51 32]';
>> weight = [55 22 10]';
>> t = table(animal, height, weight)
t =
3×3 table
animal height weight
______ ______ ______
"wolf" 110 55
"dog" 51 22
"cat" 32 10
>> https://stackoverflow.com/questions/69100771
复制相似问题