No pre-defined input in a function

Good evening,
I'm about to do some experiments and afterwards I would like to do exactly the same data processing (graphs and such), so I figured a function would be in order. However, for convenience I would like the input of the function to be dynamic, if that is possible.
So if I input name of subject A, the function loads A's data and does calculations.
My current code is:
function experiment(subjectname)
subject.data = load(subjectname);
end
And I have a script, which does nothing at the moment but try to use the function:
experiment(subjectA)
When running the script, I get the following error: "Undefined variable "subjectA" or function "experiment""
Both the experiment.m and subjectA.mat are in my MATLAB directory.

 채택된 답변

Image Analyst
Image Analyst 2013년 4월 8일

0 개 추천

You need to pass in the filename as a string.
baseFileName = 'subjectA.mat';
% folder might be pwd or whatever....
fullFileName = fullfile(folder, baseFileName);
if exist(fullFileName, 'file')
% File exists, use it
experiment(fullFileName);
else
% File doesn't exist - alert user.
errorMessage = sprintf('Warning: file not found:\n%s', fullFileName);
uiwait(warndlg(errorMessage));
end

댓글 수: 5

So instead of changing my input for the function, I change:
baseFileName = 'subjectA.mat';
to
baseFileName = 'subjectB.mat';
And this change would affect fullFileName and thereby the experiment function and the data processing which are being done?
Yes. You can make it whatever you want. You can use uigetfile() if you want, or even use sprintf:
for k = 'A' : 'Z'
baseFileName = sprintf('subject%c.mat', k)
end
Tobias
Tobias 2013년 4월 8일
Alright, I will try to implement that next time I have time to sit down with Matlab. I appreciate your feedback!
Tobias
Tobias 2013년 4월 10일
There must have been a misunderstanding somewhere in our communication. The code works nearly perfect, but rather than using the workspace values I have saved in subjectA.mat, it simply creates a variable baseFileName which equals the raw text "subjectA.mat" ..
Say subjectA.mat contains a 3 x 2 matrix - is there anyway I can make baseFileName load that data and not just the filename itself?
Your function opens the mat file and reads the contents. What you're missing is to pass it back
function subject = experiment(subjectname)
or to load it into a global variable with setappdata() or the global keyword.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Deep Learning Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by