MATLAB Answers

Fran
0

How can I append the same variables on mat file?

Asked by Fran
on 19 Apr 2019
Latest activity Commented on by Fran
on 4 May 2019 at 16:26
Hi
I need help on how to update the same variables of an exisitng mat file and alhough there are couple threads online on the subject, I still haven't found solution to the problem.
I run different instantiations of my script, which always loads the same mat file and I need my variables (of the different instantiations) to be saved in the mat file in a new row. In other words with every instantioantion of my scirpt I need a new row to me added in my mat file. How do I do this seemingly simple task? Thanks.
filename=(['my_file.mat']);
m = matfile(filename,'Writable',isWritable)
save(filename,'m.my_variables','-append');

  3 Comments

It sounds like you want to append data to your variable, not your mat file. That means you'll have to load the variable, append the data, and store the variable back into the mat file.
No, you do not need the load/append/store if you use matfile.
Thanks Rik. I tried your idea and it doesn't seem to work so far. Can you offer an example on how to use load/append/store to append the variable of the mat file with a new row of data?
Thanks

Sign in to comment.

1 Answer

Answer by Walter Roberson
on 19 Apr 2019
 Accepted Answer

After you have created m = matfile() then
new_row_of_values = something appropriate;
s = size(m, 'my_variables');
m.my_variables(s+1, :) = new_row_of_values;
Do not just use
m.my_variables(end+1, :) = new_row_of_values; %avoid this
as apparently using "end" forces the entire variable to be loaded into memory.

  5 Comments

again thanks a lot! I can create the file and write in it. Only issue is that my.variables it is not being appended to a new line, but the first line is rewritten in every instantiation of my script.
filename=('my_variables.mat');
m = matfile(filename,'Writable',true);
new_row_of_values = [normal_theta, max_theta_pwr, max_theta_freq, max_pwr, max_freq];
if isfield(m, 'my_variables')
s = size(m, 'my_variables');
m.my_variables(s(1)+1, :) = new_row_of_values;
else
m.my_variables = new_row_of_values;
end
Change the isfield() to isprop()
Worked thanks!

Sign in to comment.