Undefined function or method in function
2 views (last 30 days)
Show older comments
Fumiaki Funahashi
on 7 Feb 2015
Commented: Fumiaki Funahashi
on 8 Feb 2015
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 Comments
Accepted Answer
Roger Stafford
on 7 Feb 2015
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
More Answers (1)
John D'Errico
on 7 Feb 2015
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 Comments
See Also
Categories
Find more on Workspace Variables and MAT Files 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!