MATLAB: Problems with saving and loading inside functions

functionloadsave

Hi, I am trying to understand the logic behind the save and load commands in Matlab.
I have a script file of variables at the end of which I have created a directory ( var) and saved most of my variables. Then I have a function ( f1), inside which I have loaded the variables I need for the function. This function gives me a variable ( y1). After applying f1, I save y1 (so it overwrites what was already in var). Then I have another function (f2), which needs to use some of the variables in 'var'. but when inside f2, I try to load the variables using 'load var/x.mat' (where x is the folder where all the variables are saved), none of the variables apart from y1 are loaded (recognized).
Any hints would be appreciated.
Thanks!

Best Answer

Use the '-append' option of save so you don't blow away your existing variables inside the mat file when you save the additional variables in the same file. Like this (untested):
In function f1:
folder = 'var';
baseMatFileName = 'x.mat';
fullMatFileName = fullfile(folder, baseMatFileName);
if exist(fullMatFileName, 'file')
% Append some variables onto an existing file.
save(fullMatFileName, 'variable1', 'variable2', 'y1', 'y2', '-append');
else
% Save some variables into a new file. (This would blow away/replace an existing file.)
save(fullMatFileName, 'variable1', 'variable2', 'y1', 'y2');
end
% Save some more variables without destroying the existing ones.
save(fullMatFileName, 'y1', 'y2', '-append');
In function f2:
folder = 'var';
baseMatFileName = 'x.mat';
fullMatFileName = fullfile(folder, baseMatFileName);
if exist(fullMatFileName, 'file')
savedVarStructure = load(fullMatFileName);
% Get variable1:
variable1 = savedVarStructure.variable1;
% Get variable2:
variable2 = savedVarStructure.variable2;
% Get y1:
y1= savedVarStructure.y1;
else
warningMessage = sprintf('Mat file not found:\n%s', fullMatFileName);
uiwait(warndlg(warningMessage));
end