problems with saving and loading inside functions
1 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
Image Analyst
2012-5-28
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Workspace Variables and MAT Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!