【问题标题】:Is there a slicing operator for Matlab (Octave) structs to convert them to an array or vector of scalars and back?Matlab(Octave)结构是否有切片运算符将它们转换为标量数组或向量并返回?
【发布时间】:2012-01-08 06:07:23
【问题描述】:

在 Matlab 或 GNU Octave 中,我想做这样的事情:

x=struct('a',1,'b',2,'c',[1 2;3 4])
y=x(:) % array-ification of a struct
save -ascii y.txt y
z=load('y.txt')
x(:)=z % struct-ification of an array 

我想序列化/腌制一个结构并在以后重新创建它,以便用其他语言轻松读取/保存/操作。我更喜欢中间形式是 ascii 文本而不是二进制,以方便人类阅读/编辑/调试。

我是否忘记了一些巧妙的 (:) 式结构或元胞数组切片?

【问题讨论】:

    标签: arrays matlab vector struct octave


    【解决方案1】:

    我认为你想要的是这样的:

    x = struct('a', 1, 'b', 2, 'c', [1 2; 3 4])
    save('y.txt', '-struct', 'x', '-ascii')
    

    但我认为您不能轻松地从生成的文件中重新创建它:存在数据丢失(字段名丢失)。如果您不使用 -ascii 选项,可以使用以下命令完全重新创建它:

    save('y.mat', '-struct', 'x')
    y = load('y.mat')
    isequal(x, y) % returns true
    

    另外 load 只能加载 ASCII 文本数字的矩形数组(有关限制,请参阅 http://www.mathworks.com/help/techdoc/ref/save.htmlhttp://www.mathworks.com/help/techdoc/ref/load.html)。如果您希望将结构的字段保留在序列化形式中,您可以查看“fieldnames”函数。

    【讨论】:

    • 你说得对,我不知道如何使用硬编码模式将数组元素重新分配给字段名。由于列长度不一致,我什至无法弄清楚如何读取生成的 y.txt ascii 文件。我想我正在寻找的东西是不可能的。
    【解决方案2】:

    是的,有:),

    x=struct('a',1,'b',2,'c',[1 2;3 4])
    y=reshape([fieldnames(x) struct2cell(x)]',1,[]) % array-ification of a struct
    
    z=struct(y{:}) % struct-ification of an array 
    

    y =

    'a' [1] 'b' [2] 'c' [2x2 双倍]

    z =

    一:1

    b: 2

    c: [2x2 双倍]

    【讨论】:

    • 不幸的是,我无法弄清楚如何使用 -ascii 选项轻松保存生成的元胞数组。但这让我更接近。
    猜你喜欢
    • 2017-08-05
    • 2011-07-08
    • 2015-05-11
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多