error when writing a function

1 次查看(过去 30 天)
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
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)
try
data =evalin('base','Bathymetry');
  2 个评论
Aurelien Queffurust
Link for the doc about "Scope of a Variable":
http://www.mathworks.fr/help/techdoc/matlab_prog/f0-38052.html#f0-38068
Jan
Jan 2012-2-21
I'm convinced that recommending EVALIN will increase the confusion of a Matlab beginner.
@lestyn: I suggest to avoid EVAL, EVALIN and ASSIGNIN generally. It reduces the readibility and processing speed, while it increases the complexity of a program substantially, such that the debugging gets really cruel. Better use a clean input/output interface for the function.

请先登录,再进行评论。

更多回答(1 个)

Jan
Jan 2012-2-21
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.

类别

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