如何添加新的元素在MATLAB中结构数组? [英] How to add new element to structure array in Matlab?

查看:370
本文介绍了如何添加新的元素在MATLAB中结构数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to add new element to structure array? I am unable to concatenate with empty structure:

>> 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.

那么,这可能与空字段添加新的元素?

So is it possible to add new element with empty fields?

更新

我发现我可以添加新的元素,如果我同时增加新的领域:

I found that I can add new element if I simultaneously add new field:

>> 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

这是不可思议的,没有直通!可能有一些结肠相当于结构?

It is incredible that there is no straight way! May be there is some colon equivalent for structures?

推荐答案

您只能串联结构具有相同的字段。

You can only concatenate structures with identical fields.

让我们表示你通过第二结构b 。正如你已经检查,下面就不行,因为结构 A 有两个字段和 B 现在没有:

Let's denote your second struct by b. As you have already checked, the following won't work, because struct a has two fields and b has none:

a = struct('f1', 'hi', 'f2', 'bye');
b = struct;
[a; b]

不过,这个作品:

However, this works:

a = struct('f1', 'hi', 'f2', 'bye');
b = struct('f1', [], 'f2', []);
[a; b]

如果您想为自动创建具有相同的字段为空结构 A (而不必键入所有),您可以使用的丹的伎俩或做到这一点:

If you want to "automatically" create an empty structure with the same fields as a (without having to type all of them), you can either use Dan's trick or do this:

a = struct('f1', 'hi', 'f2', 'bye');

C = reshape(fieldnames(a), 1, []); %// Field names
C(2, :) = {[]};                    %// Empty values
b = struct(C{:});

[a; b]

我还建议阅读以下内容:

I also recommend reading the following:


  1. Stack溢出 - 什么是一些有效的方法,以两个结构
  2. 结合
  3. 堆栈溢出 - 通过另一个结构
  4. ·罗兰在MATLAB的艺术 - 串联结构

  1. Stack Overflow - What are some efficient ways to combine two structures
  2. Stack Overflow - Update struct via another struct
  3. Loren on the Art of MATLAB - Concatenating structs

这篇关于如何添加新的元素在MATLAB中结构数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆