Load M-file via function in workspace

18 次查看(过去 30 天)
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 个评论
Todd Flanagan
Todd Flanagan 2011-1-20
Herbert, I moved your response to a comment in Matt's answer.
Todd Flanagan
Todd Flanagan 2011-1-20
Also, it's a good practice to accept an answer if it helped you.

请先登录,再进行评论。

回答(2 个)

Matt McDonnell
Matt McDonnell 2011-1-20
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 个评论
Todd Flanagan
Todd Flanagan 2011-1-20
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 2011-1-20
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."

请先登录,再进行评论。


Walter Roberson
Walter Roberson 2011-1-20
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.)

类别

Help CenterFile Exchange 中查找有关 Variables 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by