error when writing a function
1 view (last 30 days)
When using a function that I have written, matlab returns the error:
Undefined function or variable 'Bathymetry'
Error in import_txt (line 58)
data = Bathymetry;
I know this stated that I haven't defined that variable but I have, I can see it in the workspace. Furthermore, the script works fine if I use it normally, this error only occurs when I try to use it as a function. What could cause this error?
Aurelien Queffurust on 21 Feb 2012
The reason is that Bathymetry variable is only known in base workspace but not in the workspace of your function (as you have already identified , see the doc for further information)
More Answers (1)
Jan on 21 Feb 2012
Please read the Getting Started chapters of the documentation, especially the articles about "functions" and "scripts". A function has its own workspace and sees only the variables, which have been delivered as inputs. E.g. in:
a = 23;
x = sin(0:0.1:2);
the value of a is not visible inside the sin function, as all internal variables of sin are not visible from the outside. This is a big benefit compared to scripts, which can see and overwrite the variables of the caller. The larger a script is, the more complicated is it to keep the overview and avoid overwriting variables used by the caller by accident.
So if you need the value of Bathymetry inside a function, append it to the list of input arguments.