How to load a variable name from one function to another?

5 次查看(过去 30 天)
Hi, I am writing a script in which I call 4 separate functions. I am using the following:
function dat = run_experiment(varargin)
dat.subj = input('Enter Participant Code here');
run_test
run_introduction
run_prepost_test
run_training
end
However, dat.subj is called upon in each function in order to save the filename based on which test it is and it uses the current time. For example, this is in run_introduction:
dat.fileName = [dat.subj '_' dat.test_type '_' dat.timeNow '.mat'];
Every time I run the run_experiment and enter a participant ID for dat.subj, it doesnt seem to carry over when run_introduction begins. I get the error:
'Reference to non-existent field 'subj'.
Does anyone have any tips on how to call a variable from a different function? I cannot load it from the workspace, since the file it creates is contingent on the subject ID and the time now.
Thanks!
  1 个评论
James Tursa
James Tursa 2018-1-22
编辑:Stephen23 2018-1-23
Please confirm that the files run_test, run_introduction, run_prepost_test, and run_training are all functions and not scripts. And if they are functions, why can't you just pass in the dat variable as an argument? E.g.,
dat = run_introduction(dat);
And then in the file run_introduction.m:
function dat = run_introduction(dat)

请先登录,再进行评论。

回答(1 个)

Stephen23
Stephen23 2018-1-23
编辑:Stephen23 2018-1-23
"How to load a variable name from one function to another?"
By far the simplest and most efficient way of doing this is to pass input/output arguments. This is trivially simple: you do this every time you call sin, sqrt, plot, or any other MATLAB function. You can easily write your own functions to do the same, as shown in the function help:
This means all you need to do is define your function something like this:
function dat = run_test(dat)
and call it like this:
dat = run_test(dat);
If passing input and output arguments is not possible (this would be very unusual), then there are other good options, such as writing nested functions (these would work nicely in your situation). You will find the complete list of ways to pass variables here:
You might also like to read about how to parametrize functions, if you are using it with some kind of optimization routine:
In any case you should definitely avoid using global variables or using evalin or assignin: these are how beginners force themselves into writing slow, buggy, complex code that is very hard to debug. Read more here:

类别

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