Undefined function or method in function
조회 수: 5 (최근 30일)
이전 댓글 표시
I have a custom function below (simplified) named "my_fun", and both y1 and Observed are 10 by 1 matrix. Why do I get the error saying "Undefined function or method "Observed"? Thanks for your support!
function z = my_fun(y1) z = sum(abs(Observed-y1).^2);
>> Observed
Observed =
31.6064
32.2017
30.4732
28.6939
28.3150
29.6229
31.1920
32.2839
31.1575
28.5715
>> y1
y1 =
4.6829
4.8186
3.2822
1.4864
1.0822
2.4412
4.3140
4.9787
3.8242
1.9120
>> my_fun Undefined function or method 'Observed'
error : my_fun (line 2) z = sum(abs(Observed-y1).^2);
댓글 수: 0
채택된 답변
Roger Stafford
2015년 2월 7일
Since you are not passing 'Observed' to 'my_fum' as a function argument, you must make its value known to the function as a parameter in some manner. Read:
http://www.mathworks.com/help/optim/ug/passing-extra-parameters.html
추가 답변 (1개)
John D'Errico
2015년 2월 7일
Because the vector Observed does not exist inside the function workspace.
Functions have their own workspace. They cannot see arrays from the caller workspace, or from the base workspace. This is true unless the function is a nested one, when it can also see variables from the parent workspace.
This is why functions allow arguments, so you can then pass in variables as needed. You did pass in y1. Why not pass in Observed also as the second argument?
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!