필터 지우기
필터 지우기

Load M-file via function in workspace

조회 수: 8 (최근 30일)
Herbert Walter
Herbert Walter 2011년 1월 20일
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에서 Interactive Control and Callbacks에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by