Load M-file via function in workspace

17 views (last 30 days)
Herbert Walter
Herbert Walter on 20 Jan 2011
As I have many .mat files with measure data I'd like to write a function wich loads the chosen file, and plots the values from chosen columns in the matrix.
I tried:
% creates a function called 'measuredata'
function measuredata(nameoffile)
load(nameoffile)
end
but if I type in the command window, and want to load e.g. measurement102.mat:
>> measuredata('measurement102')
I get no warning but nothing is being loaded to the workspace. What can I do?
  2 Comments
Todd Flanagan
Todd Flanagan on 20 Jan 2011
Herbert, I moved your response to a comment in Matt's answer.
Todd Flanagan
Todd Flanagan on 20 Jan 2011
Also, it's a good practice to accept an answer if it helped you.

Sign in to comment.

Answers (2)

Matt McDonnell
Matt McDonnell on 20 Jan 2011
Each function defines its own workspace that is used to evaluate commands and store the results in local variables. This differs from scripts, which manipulate the base workspace directly.
The data is loaded into the workspace of the function measuredata, which then returns to the base workspace without returning any output.
To return the data to the base workspace use:
function data = measuredata(nameoffile)
data = load(nameoffile);
% Do some plotting and analysis...
end
  2 Comments
Todd Flanagan
Todd Flanagan on 20 Jan 2011
Herbert says, "But then I just get the "ans" variable in the workspace.. How can I load excactly the measurement102.mat to the workspace?"
Todd Flanagan
Todd Flanagan on 20 Jan 2011
Matt responds, "Call the function from the MATLAB command line as
data = measuredata('measurement102');
This will create a struct called data in the workspace. You can then access the values using data.x, data.y, or whatever the names of the values in the mat file were."

Sign in to comment.


Walter Roberson
Walter Roberson on 20 Jan 2011
As the file might contain multiple variables, the easiest way to duplicate the effect of loading them into the workspace of the caller is to use
% creates a function called 'measuredata'
function measuredata(nameoffile)
evalin('caller', sprintf('load(''%s'')',nameoffile))
end
This is not a good solution; using Matt's version and assigning the output to a variable and accessing the fields of that variable is much cleaner. The version I show here should only be used if it is important that random variables in the caller's workspace should be clobbered if they just happen to have the same name as a variable name saved in the file, or if it is important that Strange Things happen if a function used in the calling function has the same name as the name of a variable saved in a file. (And yes, some people do rely upon these kinds of oddities, unfortunately.)

Categories

Find more on Variables in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!