Matlab(Octave)结构是否有切片运算符将它们转换为标量数组或向量并返回?

发布于 2024-12-18 11:06:12 字数 347 浏览 2 评论 0原文

在 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 

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

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

In Matlab or GNU Octave I'd like to do something like this:

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 

I want to serialize/pickle a structure and recreate it later, allowing easy read/save/manipulate in other languages. I'd prefer the intermediate form to be ascii text rather than binary to facilitate human reading/editing/debugging.

Am I forgetting some clever (:)-like slicing for structs or cell arrays?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晨敛清荷 2024-12-25 11:06:13

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

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

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

I think what you want is something like:

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

But I do not think you can easily recreate it from the resulting file: there is data loss (the fieldnames are lost). If you don't use the -ascii option, it can be fully recreated using:

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

Additionally load can only load a rectangular array of numbers of ASCII text (see http://www.mathworks.com/help/techdoc/ref/save.html and http://www.mathworks.com/help/techdoc/ref/load.html for the limitations). If you wish to keep the fields of the struct in your serialized form, you might look into the "fieldnames" function.

栩栩如生 2024-12-25 11:06:13

是的,有:),

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

Yes, there is :),

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

z =

a: 1

b: 2

c: [2x2 double]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文