在matlab中向数据结构添加数据点
Adding a datapoint to datastruct in matlab
我正在尝试向现有数据结构添加数据点。我创建了以下数据结构。
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
数组而不是 cellstrs 来存储您的字符串数据。他们几乎在所有方面都更好(性能除外)。用双引号获取它们:
>> 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
>>
我正在尝试向现有数据结构添加数据点。我创建了以下数据结构。
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
数组而不是 cellstrs 来存储您的字符串数据。他们几乎在所有方面都更好(性能除外)。用双引号获取它们:
>> 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
>>