How to append a field to an existing structure in a mat file?

s.a = rand;
s.b = rand(2);
save('s.mat','s')
load s
s.c = 'yes'
save('s.mat','s') % now the new field is added
Is there any other alternatives?, the '-append' flag is there not sure how to yield success though.

2 commentaires

save(filename,variables,'-append') adds new variables to an existing file.
If a variable already exists in a MAT-file, then save overwrites it with the
value in the workspace.
A struct as the whole is the variable, not a field within the structure.
If the alternative includes that the new data be actually part of an existing struct variable, then I think the answer is "no".
If you would be content with just saving an additional variable but outside the already defined struct, then -append does the job.
If the variable were just an array, matfile would allow indexing including, I believe, extending the size but can't write the dot indexing expression to address a field of a struct
madhan ravi
madhan ravi le 15 Août 2019
Modifié(e) : madhan ravi le 15 Août 2019
Thanks a lot, dpb. Had the same thoughts :).

Connectez-vous pour commenter.

Réponses (1)

clear s
s.a = rand;
s.b = rand(2);
save('s.mat','-struct', 's', '-v7.3');
s = matfile('s.mat', 'writable', true);
s.c = 'yes';
clear s
whos -file s.mat

4 commentaires

Thank you , sir Walter. The role of -v7.3 is significant.
Bruno Luong
Bruno Luong le 15 Août 2019
Modifié(e) : Bruno Luong le 15 Août 2019
dpb is correct, I think Walter solution does not exactly question asked. This will save 'a' 'b' as variables and not inside the structure internally stored inside the matfile..
save('s.mat','-struct', 's', '-v7.3')
It just trick the load by MATFILE later inside a structure but there is no internal field add inside thet MATFILE.
It does not do more than
s.a = rand;
s.b = rand(2);
save('s.mat','-struct', 's')
c='yes'
save('s.mat','-append', 'c')
It does a bit more in that there is no need to explicitly save(): as soon as you create the reference, the new variable is written into the .mat file.
Thanks, Bruno. I didn't notice it properly.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Variables dans Centre d'aide et File Exchange

Produits

Version

R2018b

Question posée :

le 15 Août 2019

Commenté :

le 15 Août 2019

Community Treasure Hunt

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

Start Hunting!

Translated by