Function handle is giving wrong results!

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

the cyclist
the cyclist 2016년 5월 28일
Can you be more specific about what is "clearly wrong"? Do you mean the value of f(x,a0,a1) is not what you expect? What value did you get, and what did you expect to get?
Ahmad
Ahmad 2016년 5월 28일
편집: Ahmad 2016년 5월 28일
What I mean is substituting x and a1 and a2 values by hand, gives different results than matlab, for example, x = 1, a1 =2, x/(x+a1)=1/3, please run the code and see what u get!
Any code that uses "clear all" is clearly wrong. "clear all" does a lot more than you expect.

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

답변 (2개)

the cyclist
the cyclist 2016년 5월 28일
편집: the cyclist 2016년 5월 28일

0 개 추천

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.
If you don't understand why, read this documentation page about array vs. matrix operations.
the cyclist
the cyclist 2016년 5월 28일

0 개 추천

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.

댓글 수: 1

Ahmad
Ahmad 2016년 5월 28일
found it, partialf_a0(a1,x) is not the same as partialf_a0(x,a1)

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

카테고리

도움말 센터File Exchange에서 Printing and Saving에 대해 자세히 알아보기

질문:

2016년 5월 28일

댓글:

2016년 5월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by