Can anyone explain how can this happen?

조회 수: 1 (최근 30일)
Ray Lee
Ray Lee 2016년 4월 4일
댓글: Ray Lee 2016년 10월 12일
function myfunctest
subfcn_set('notafunc');
whos
which notafunc
notafunc
subfcn_set('sin');
whos
which sin
sin
end
function subfcn_set(n)
assignin('caller', n, ['I am ',n]);
end
running myfunctest in matlab gives
>> myfunctest
Name Size Bytes Class Attributes
notafunc 1x13 26 char
notafunc is a variable.
notafunc =
I am notafunc
Name Size Bytes Class Attributes
notafunc 1x13 26 char
sin 1x8 16 char
sin is a variable.
Error using sin
Not enough input arguments.
Error in myfunctest (line 13)
sin
The builtin sin function is called even when a local variable "sin" exists.

채택된 답변

Ray Lee
Ray Lee 2016년 4월 4일
I found the doc.
Another potential source of name conflicts occurs when you define a function that calls load or eval (or similar functions) to add variables to the workspace. In some cases, load or eval add variables that have the same names as functions. Unless these variables are in the function workspace before the call to load or eval, the MATLAB parser interprets the variable names as function names.
  댓글 수: 2
Guillaume
Guillaume 2016년 4월 4일
Of course, the advice to avoid creating variables with the same name as a function is not really useful since the names of existing functions depends on which toolbox you have and whichever code is in your path.
If only matlab had a proper namespace system...
Ray Lee
Ray Lee 2016년 10월 12일
+1 for Guillaume's comment

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2016년 4월 4일
If you put a breakpoint on the sin line and execute it from the debugger the error does not occur, so I suspect it's a 'bug' with the Just-In-Time compiler introduced recently. I assume that when it loads the function, the JIT compiler sees that there is no sin variable created in the function so assumes that sin is a function call.
While it's a bug, it's also another reason for avoiding dynamic variable creation using eval, assignin, and their ilk.

카테고리

Help CenterFile Exchange에서 Antennas, Microphones, and Sonar Transducers에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by