Undefined function or method in function

2 次查看(过去 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);

采纳的回答

Roger Stafford
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
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?

类别

Help CenterFile 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!

Translated by