我试图添加一个数据点到现有的数据结构。我已经创建了以下数据结构:
ourdata.animal= {'wolf', 'dog', 'cat'}
ourdata.height = [110 51 32]
ourdata.weight = [55 22 10]
假设我想添加另一个名称为'fish'
,高度为3
,权重为1
的数据结构,我该怎么做?
您可以简单地将它附加到结构的末尾:
ourdata.animal{end+1} = 'fish'
ourdata.height(end+1) = 3
ourdata.weight(end+1) = 1
如果您想使用多个结构,可以编写一个小函数来组合多个结构中的字段值。这里有一个例子,使用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
数组而不是单元格来存储字符串数据。他们在几乎所有方面都更好(除了性能)。用双引号括起来:
>> strs = ["wolf" "dog" "cat"]
strs =
1×3 string array
"wolf" "dog" "cat"
>>
同样,考虑使用table
数组而不是struct数组来处理像这样的表格数据。桌子很漂亮!
>> 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
>>