如何将 1 个结构字段保存在另一个已保存的结构及其字段中
How to Save 1 Structure Field Inside another Saved Structure with its Fields
虽然有类似的帖子,但我还没有看到这种在结构中保存结构的场景。
我的目标是:将一个结构字段保存在一个已定义的已保存结构中。
我的水果结构已经保存在它的文件夹(.mat)中,里面是:
fruit =
struct with fields:
apples: 5
oranges: 2
pineapple: 1
我的目标是在已保存的结构中添加一个葡萄园。
fruit =
struct with fields:
apples: 5
oranges: 2
pineapple: 1
grapes: 13
这是我的代码:
clc;
clear all;
fruit.apples = 5
fruit.oranges = 2
fruit.pineapple = 1
save('fruit.mat', '-struct', 'fruit')
clear all;
load('fruit.mat')
fruit.grapes = 13
save('fruit.mat', '-struct', 'fruit')
输出:仅保存葡萄田,不保存其他田地:苹果、橙子和菠萝。
目标输出:如何将所有 4 个字段保存在相同的水果结构中?
您要么在保存到 mat 文件时需要省略 '-struct'
参数:
...
save('fruit.mat', 'fruit');
clear all;
load('fruit.mat');
fruit.grapes = 13;
save('fruit.mat', 'fruit');
或者将 load
的结构输出放入变量 fruit
:
...
save('fruit.mat', '-struct', 'fruit');
clear all;
fruit = load('fruit.mat');
fruit.grapes = 13;
save('fruit.mat', '-struct', 'fruit');
当您为 load
添加 '-struct'
argument before a variable containing a structure, the save
function will store the fields of that structure as individual variables in the file instead of storing the structure as one variable. So, in the second option above, the file "fruit.mat" will contain three variables: apples
, oranges
, and pineapple
. Calling load
with no output will simply create these three variables in the workspace, not contained in a structure. You can collect all of the variables in a file into a structure by specifying an output 时。
虽然有类似的帖子,但我还没有看到这种在结构中保存结构的场景。
我的目标是:将一个结构字段保存在一个已定义的已保存结构中。
我的水果结构已经保存在它的文件夹(.mat)中,里面是:
fruit =
struct with fields:
apples: 5
oranges: 2
pineapple: 1
我的目标是在已保存的结构中添加一个葡萄园。
fruit =
struct with fields:
apples: 5
oranges: 2
pineapple: 1
grapes: 13
这是我的代码:
clc;
clear all;
fruit.apples = 5
fruit.oranges = 2
fruit.pineapple = 1
save('fruit.mat', '-struct', 'fruit')
clear all;
load('fruit.mat')
fruit.grapes = 13
save('fruit.mat', '-struct', 'fruit')
输出:仅保存葡萄田,不保存其他田地:苹果、橙子和菠萝。
目标输出:如何将所有 4 个字段保存在相同的水果结构中?
您要么在保存到 mat 文件时需要省略 '-struct'
参数:
...
save('fruit.mat', 'fruit');
clear all;
load('fruit.mat');
fruit.grapes = 13;
save('fruit.mat', 'fruit');
或者将 load
的结构输出放入变量 fruit
:
...
save('fruit.mat', '-struct', 'fruit');
clear all;
fruit = load('fruit.mat');
fruit.grapes = 13;
save('fruit.mat', '-struct', 'fruit');
当您为 load
添加 '-struct'
argument before a variable containing a structure, the save
function will store the fields of that structure as individual variables in the file instead of storing the structure as one variable. So, in the second option above, the file "fruit.mat" will contain three variables: apples
, oranges
, and pineapple
. Calling load
with no output will simply create these three variables in the workspace, not contained in a structure. You can collect all of the variables in a file into a structure by specifying an output 时。