error when writing a function

1 view (last 30 days)
Richard
Richard on 21 Feb 2012
Edited: Azzi Abdelmalek on 18 Oct 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?

Accepted Answer

Aurelien Queffurust
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)
try
data =evalin('base','Bathymetry');
  2 Comments
Jan
Jan on 21 Feb 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.

Sign in to comment.

More Answers (1)

Jan
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.

Categories

Find more on Loops and Conditional Statements 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!

Translated by