save new field to a structure?!

23 ビュー (過去 30 日間)
Ano
Ano 2017 年 7 月 12 日
回答済み: Thomas 2018 年 3 月 15 日
Hello! I have a 'myfile.mat' which contains several structures struct1, struct2,... Now I would like to save a new added field to one of the structures let say struct1 but it is not working when reloading the .mat file the newfield is not there, any suggestions ?! thank you !
  2 件のコメント
Geoff Hayes
Geoff Hayes 2017 年 7 月 12 日
Ano - are you saving the updated structure? Please show the code that you have written to read the myfile.mat, update the (say) struct1, and then save the data back to file.
Adam
Adam 2017 年 7 月 12 日
You haven't included any code as to how you do it which would make it a lot easier for us to know where you are going wrong.

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

採用された回答

Steven Lord
Steven Lord 2017 年 7 月 12 日
There are a couple good ways to do this. If your MAT-file has a lot of data stored in it, save using the -append flag. Another approach, particularly if you need to modify more than one of the struct arrays stored in the MAT-file, is to load into a struct and save that struct using the -struct flag.
data = load('myfile.mat');
data.struct1.newfield = 42;
save('myfile.mat', '-struct', 'data')
With this approach you don't need to worry about overwriting a variable in your workspace that happens to have the same name as one of the variables in the MAT-file.

その他の回答 (2 件)

Thomas
Thomas 2018 年 3 月 15 日
Try looking at the function "matfile" in help. Matfiles are treated differently than other files, and you may need to set the 'Writable' property to true (Good Luck!). Example:
m = matfile('myfile.mat','Writable',true);
m.struct1.newfield = newfield;

Ano
Ano 2017 年 7 月 12 日
I have been googling for almost one hour but no result, this is the code that I am using to save the new added field but I lose all the other structures in my .mat file any ideas ?! thank you!
load ('myfile.mat','struct1')
struct1.newfiled = myMatrix;
save myfile struct1

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by