problems with saving and loading inside functions

조회 수: 1 (최근 30일)
Hooman
Hooman 2012년 5월 28일
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!

채택된 답변

Image Analyst
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 CenterFile 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!

Translated by