how to append variables in a specific .mat file in a specific path
Show older comments
greeting
how to append variables in a specific .mat file in a specific path
[FileName,PathName] = uigetfile('*.mat','Select the Rotor DATA file')
FileName =
Data.mat
PathName =
C:\Users\PC\Desktop\
i need to add variabls to Data.mat using UI
plz help
Accepted Answer
More Answers (1)
Wonsang You
on 3 Jun 2017
Assume that you want to save Var into 'data.mat'. Run the following code.
Var = 3;
A = load('data.mat');
save('data.mat','A','Var');
1 Comment
Walter Roberson
on 3 Jun 2017
Edited: Walter Roberson
on 3 Jun 2017
That does not append.
When you have a .mat and you load() and assign that to a variable, then the resulting variable will be a scalar struct in which there was one field for every existing variable in the .mat file.
Your save('data.mat','A','Var') would overwrite the file, but the new contents would be exactly two variables, one named 'Var' and the other a structure named 'A'.
For example suppose the file originally contained variables 'A', 'B', and 'C'. Then
A = load('data.mat');
would result in a scalar struct A with fields 'A', 'B', and 'C'. So A.A would refer to what was previously the variable A in the file, A.B would refer to what was previously the variable B in the file, and A.C would refer to what was previously the variable C in the file.
When you then save('data.mat','A','Var') then the result in the .mat file would be 'Var' and this structure 'A'. You would have to know what had happened to the file so that you could know that now to refer to the old B you would have to load variable A from data.mat and refer to A.B . Whereas what you would want is that instead after 'Var' was appended, that the file would contain 'A' (the original), 'B', 'C', and 'Var'.
What you could do is
Var = 3;
A = load('data.mat');
A.Var = Var;
save('data.mat', '-struct', 'A');
The result of that would be to take the variable A and extract the fields from it and write each as a variable, thereby creating a file with 'A' (the original), 'B', 'C', and 'Var' stored in it. This approach would overwrite the entire file, rather than just updating the minimal part of it to write the new variable Var. Also, it requires you have enough free memory to be able to load the entire .mat . There is also the risk that you could end up changing .mat version -- for example if the file was a -v7.3 mat but your preference for the default save format is the old -v5.3 then the result of the save() would be a -v5.3 file because you would be overwriting all of the old file.
Categories
Find more on Workspace Variables and MAT Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!