Function handle is giving wrong results!
2 次查看(过去 30 天)
显示 更早的评论
This code is clearly giving wrong results:
clc;clear all
a0 = 2;
a1 = 2;
y = [1 1.4 2.3];
x = [1 2 3];
f = @(x,a0,a1) (a0.*x)/(a1+x);
partialf_a0 = @(x,a1) (x./(x+a1));
partialf_a1 = @(x,a0,a1) (-(a0.*x)/((a1+x).^2));
partialf_a0(a1,x)
partialf_a1(x,a0,a1)
f(x,a0,a1)
Substituting a0 and a1 with their values into the equations, gives correct results for partialf_a0:
clc;clear all
a0 = 2;
a1 = 2;
y = [1 1.4 2.3];
x = [1 2 3];
f = @(x,a0,a1) (a0.*x)/(a1+x);
partialf_a0 = @(x,a1) (x./(2+x));
partialf_a1 = @(x,a0,a1) (-(a0.*x)/((a1+x).^2));
partialf_a0(x)
partialf_a1(x,a0,a1)
3 个评论
Walter Roberson
2016-5-28
Any code that uses "clear all" is clearly wrong. "clear all" does a lot more than you expect.
回答(2 个)
the cyclist
2016-5-28
编辑:the cyclist
2016-5-28
Just a guess, but where you did
f = @(x,a0,a1) (a0.*x)/(a1+x);
maybe you really want
f = @(x,a0,a1) (a0.*x)./(a1+x);
[Notice the "./" instead of "/".]
Similarly for your other functions.
0 个评论
the cyclist
2016-5-28
Please, as I asked earlier, tell us what you get and what you expect to get. I ran this simplified version of your code
f = @(x,a0,a1) (a0.*x)./(a1+x);
f(1,1,2)
The displayed answer is 0.3333. This is the answer I would expect to get.
I am trying to understand what you think would be different. One possibility is that you are getting confused about variable values that are defined before you define the function, which may be irrelevant because the function arguments will be used instead.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!