Function does not assigin the variable to the workspace
Show older comments
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 Comments
Azzi Abdelmalek
on 4 Jun 2013
Can you provide more informations
Image Analyst
on 4 Jun 2013
I don't know that that is enough information for us to solve your problem. Are both functions in the same m-file? What are the names of the two functions (the former script that is now a function, and the function that the script called)?
Giorgos Papakonstantinou
on 4 Jun 2013
Giorgos Papakonstantinou
on 4 Jun 2013
Accepted Answer
More Answers (1)
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 Comments
Giorgos Papakonstantinou
on 4 Jun 2013
Image Analyst
on 5 Jun 2013
Excellent description Jan. Giorgios, what's to prevent you from asking yes/no via questdlg() in your code when you want the user intervention? Also, don't use read() as a function name since it's the name of a built in function used for reading videos, among other things.
Giorgos Papakonstantinou
on 6 Jun 2013
Jan
on 6 Jun 2013
@Giorgos: Unfortunately comments cannot trigger messages at the moment.
Categories
Find more on Data Type Identification in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!