Borrar filtros
Borrar filtros

error when writing a function

1 visualización (últimos 30 días)
Richard
Richard el 21 de Feb. de 2012
Editada: Azzi Abdelmalek el 18 de Oct. de 2013
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?

Respuesta aceptada

Aurelien Queffurust
Aurelien Queffurust el 21 de Feb. de 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)
try
data =evalin('base','Bathymetry');
  2 comentarios
Aurelien Queffurust
Aurelien Queffurust el 21 de Feb. de 2012
Link for the doc about "Scope of a Variable":
http://www.mathworks.fr/help/techdoc/matlab_prog/f0-38052.html#f0-38068
Jan
Jan el 21 de Feb. de 2012
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.

Iniciar sesión para comentar.

Más respuestas (1)

Jan
Jan el 21 de Feb. de 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.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by