Function does not assigin the variable to the workspace
2 次查看(过去 30 天)
显示 更早的评论
I have created a script that calls a function and the last one assigns in the workspace a variable and this works perfectly.
I am trying to turn the first script into function. In this case I get an error:
Undefined function or variable 'st'.
'st' is the variable that is assigned in the script. But when I turn it into a function then the variable is no more assigned.
Why?
4 个评论
采纳的回答
Matt J
2013-6-4
编辑:Matt J
2013-6-4
assignin('base','st',st)
will send 'st' to the workspace of the command line. It will not send it to the workspace of any arbitrary function that you want. You should use the GUIDATA command when st is generated to store it among the rest of the GUI's data. Then use GUIDATA again to retrieve it in the function that does
choice(n)=st;
2 个评论
Iain
2013-6-5
You need the handle of an item on the gui. If you have that you can put any information you like into the "Userdata" property:
set(handle,'Userdata',variable)
更多回答(1 个)
Jan
2013-6-4
编辑:Jan
2013-6-4
Let me guess the details (but please post more details in the future even when this guess is successful):
The script file test.m:
st = 23
Now you type in the command window:
test % Script is called
st % 23 is replied
Then you convert the script to a function:
function test
st = 23
And call it from the command window:
clear st % cleanup
test % function is called
st % ERROR: Undefined
Or perhaps you've considered the output already:
function st = test
st = 23
And call it from the command line:
test % function is called
st % ERROR: Undefined
Still an error, but why? st is created inside the function, but it is the purpose of functions to keep the definitions inside except for the exported outputs. But these outputs must be caught be the caller:
st = test
st % Replies 23
The name need not be equal:
abc = test
abc % Replies 23
The behavior of functions is explained in the Getting Started chapters of the documentation. It is worth to read them, when you want to use such a powerful language as Matlab. It is not the intention of the forum (but obviously mine in this evening) to repeat the basics, which are written down exhaustively in the docs already.
4 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Identification 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!