structure is pointlessly nested within itself when I save it. How to unnest?

13 ビュー (過去 30 日間)
Alexei M
Alexei M 2020 年 6 月 16 日
コメント済み: Fangjun Jiang 2020 年 6 月 17 日
Maybe kind of a stupid question, but I had a structure saved to disk--let's call it data1.mat. My script would have a few lines like this:
data1 = load('data1.mat');
...
There would be a few of these. Then my script commands would access variables like this:
some_command(data1.some_variable)
I edited some numbers and wanted to update the saved file data1.mat. However, now when I load the updated file, it now has an extra "layer" of "data1". So to access a variable I now need to do:
some_command(data1.data1.some_variable)
This is stupid. How can I undo this?? This should be simple but for some reason I can't figure out how to remove the pointless extra level. I tried selecting all the fields inside the structure layer and saving them to disk, but the same thing happened.

採用された回答

Steven Lord
Steven Lord 2020 年 6 月 16 日
When you save the struct that you received from load after modifying it, use the '-struct' option in your save call.
>> x = 1:10;
>> y = magic(5);
>> S = struct('x', x, 'y', y);
>> save('mymatfile.mat', '-struct', 'S');
>> whos -file mymatfile.mat
Name Size Bytes Class Attributes
x 1x10 80 double
y 5x5 200 double

その他の回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2020 年 6 月 16 日
If you use load() without returning a variable, then the structure won't be created, but then you have to know what variables are in the .mat file. try this:
clear;
a=1;
b=2;
save;
clear
load;
whos
clear
data1=load;
whos
  4 件のコメント
Alexei M
Alexei M 2020 年 6 月 16 日
Ok I got it.
Loaded it without output variable as you said. Then I looped through the structure and used the
eval
command to recreate all the fields as variables in the workspace and then selected them all and saved them.
Fangjun Jiang
Fangjun Jiang 2020 年 6 月 17 日
Don't use eval. If your data comes already in a structure, no need to re-create those variables. See Steven's answer.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT-Files についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by