Variables not saved after function completes. Help needed

조회 수: 9 (최근 30일)
Rick
Rick 2012년 10월 14일
Hi all,
I have this function in checkfile.m
function [] = checkfile(filename, pathname)
if isequal(filename,0)
warndlg('File not selected.', 'Warning!', 'modal');
else
cd(pathname);
load(filename); % load variables
end
end
Inside this file, there are a number of variables. When this function completes, the variables are deleted. I do not want to save the variables as an array.
For example, inside file1.mat, there are 3 variables, a,b & c.
I want these 3 variables, a,b & c to be in the workspace as it is after the function exits.
How can I make the functions such that the variables do not delete itself after the function exits.

채택된 답변

Arthur
Arthur 2012년 10월 14일
The cleanest (and probably fastest) method is to let load(filename) store into a variable, and let the function return this variable. So like this
function myData = checkfile(filename, pathname)
if isequal(filename,0)
warndlg('File not selected.', 'Warning!', 'modal');
myData = [];
else
cd(pathname);
myData = load(filename); % load variables
end
end
Note that I also added myData = [] for the case that there was no file selected. Otherwise your function would fail in this case.
myData will be a structure containing all the variables of the file. So in your case it will contain myData.a, myData.b and myData.c.

추가 답변 (2개)

José-Luis
José-Luis 2012년 10월 14일
Have the function return the variables you want to keep, otherwise they are destroyed upon exit.
function [a,b,c] = checkfile(filename,pathname)
%etc
  댓글 수: 1
Rick
Rick 2012년 10월 14일
I see.
I have the same numbers of variables for each file. But the names are all different.
As such, i want to save the variables as what they were named.

댓글을 달려면 로그인하십시오.


Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 14일
편집: Azzi Abdelmalek 2012년 10월 14일
In your function use
data=load(filename)
If filname.mat contains variables x y and z, you can get them, after caling your function
data= checkfile(filename,pathname)
by:
x=data.x
y=data.y
z=data.z
and don't forget to change, like mentioned by José luis
function data=checkfile(filename,pathname)

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by