Effacer les filtres
Effacer les filtres

How to append new structure array element in existing .mat file.

59 vues (au cours des 30 derniers jours)
Abdurrehman
Abdurrehman le 1 Fév 2017
Commenté : Jan le 2 Fév 2017
I am appending new structure array element in existing .mat file (which contains structures), it saves new element accurately but previous values are replaced with empty elements. as stated below
FileName=fullfile('\\Server Location Address');% Address of existing .mat file
Device(5)=struct('A',1,'B',2,'C',3);
save(FileName,'Device','-append');
The above code save Device(5) elements accurately but it removes all Devices values before 5.
Please help how to append new value in .mat file while don't changing previous ones.
Thanks
  2 commentaires
Stephen23
Stephen23 le 1 Fév 2017
Modifié(e) : Stephen23 le 1 Fév 2017
The badly named '-append' option should really be named the '-replace' option. It does not append data onto existing arrays, as the save documentation clearly states: "adds new variables to an existing file. If a variable already exists in a MAT-file, then save overwrites it."
When beginners start to read the documentation then they start to learn how MATLAB works, and they don't have to guess what MATLAB is doing.
Not only that this is such a common topic that it has hundreds of threads already on this forum. This simple search (you can search Answers at the top of the page) gives more than five hundred results:
Did you read any of them?
Muhammad Abdurrehman
Muhammad Abdurrehman le 1 Fév 2017
Read some of them but couldn't found a way that how to append new structure element in existing .mat file

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 1 Fév 2017
Modifié(e) : Stephen23 le 1 Fév 2017
You might find that matfile is the easiest way. There are lots of examples and help in the documentation, but depending on your data something like this should work:
m = matfile(filename,'Writable',true);
m.device = [m.device,newdata];
or perhaps
m = matfile(filename,'Writable',true);
m.device(end+1) = newdata;

Plus de réponses (1)

Jan
Jan le 1 Fév 2017
If the MAT file is not written in the -v7.3 version, this can help:
FileName = fullfile('\\Server Location Address');
FileData = load(FileName, 'Device');
Device = FileData.Device;
Device(5) = struct('A',1, 'B',2, 'C',3);
save(FileName, 'Device', '-append');
  2 commentaires
Muhammad Abdurrehman
Muhammad Abdurrehman le 2 Fév 2017
Thanks for the answer but I am using -v7.3
Jan
Jan le 2 Fév 2017
Fine, then Stephen's solution is perfect. Perhaps another reader has to work with files in another format, such that this approach might be useful.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by