Function does not assigin the variable to the workspace
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Matt J
am 4 Jun. 2013
Bearbeitet: Matt J
am 4 Jun. 2013
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 Kommentare
Iain
am 5 Jun. 2013
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)
Weitere Antworten (1)
Jan
am 4 Jun. 2013
Bearbeitet: Jan
am 4 Jun. 2013
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 Kommentare
Siehe auch
Kategorien
Mehr zu Data Type Identification finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!