首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在matlab中向datastruct添加一个数据点

在matlab中向datastruct添加一个数据点
EN

Stack Overflow用户
提问于 2021-09-08 09:50:52
回答 2查看 37关注 0票数 0

我正在尝试将一个数据点添加到现有的数据结构中。我已经创建了以下数据结构。

代码语言:javascript
运行
复制
ourdata.animal= {'wolf', 'dog', 'cat'}
ourdata.height = [110 51 32]
ourdata.weight = [55 22 10]

假设我想要向数据结构中添加另一个名称为'fish' height 3和weight 1的对象,该如何操作?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-09-08 10:05:52

您可以简单地将其附加到结构的末尾:

代码语言:javascript
运行
复制
ourdata.animal{end+1} = 'fish'
ourdata.height(end+1) = 3
ourdata.weight(end+1) = 1
票数 2
EN

Stack Overflow用户

发布于 2021-09-18 15:40:35

如果您想处理多个结构,可以编写一个小函数来组合多个结构中的字段的值。下面是一个示例,使用fieldnames()发现存在哪些字段:

代码语言:javascript
运行
复制
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

其工作原理如下:

代码语言:javascript
运行
复制
>> 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来存储字符串数据。它们在几乎所有方面都更好(除了性能)。使用双引号获取它们:

代码语言:javascript
运行
复制
>> strs = ["wolf" "dog" "cat"]
strs = 
  1×3 string array
    "wolf"    "dog"    "cat"
>> 

另外,对于类似于表格的数据,可以考虑使用table数组而不是结构数组。桌子很不错!

代码语言:javascript
运行
复制
>> 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  
>> 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69100771

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档