error when writing a function

조회 수: 1 (최근 30일)
Richard
Richard 2012년 2월 21일
편집: Azzi Abdelmalek 2013년 10월 18일
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
Aurelien Queffurust 2012년 2월 21일
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
Aurelien Queffurust 2012년 2월 21일
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에서 Whos에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by