필터 지우기
필터 지우기

Trouble with my function

조회 수: 1 (최근 30일)
lilo moutila
lilo moutila 2021년 1월 9일
댓글: Star Strider 2021년 1월 9일
I want to run this code:
syms x
syms y(x)
y(x) = 5*(x^2);
values = 4;
h = 1;
derivative(5,1)
function yd = derivative(values, h)
syms y(x)
yd = (y(values + h) - y(values - h)) / (2*h);
end
But instead of getting the real value ( in this case 40 ), I got :
ans =
y(6)/2 - y(4)/2
How can I solve this please.

답변 (1개)

Star Strider
Star Strider 2021년 1월 9일
You need to tell your ‘derivative’ function what ‘y’ is.
Changing ‘derivative’ to an anonymous function (for my convenience) and otherwise leaving it unchanged (except to add ‘y’ as an argument):
syms x y(x)
derivative = @(values, h, y) (y(values + h) - y(values - h)) / (2*h);
y(x) = 5*(x^2);
values = 4;
h = 1;
Result = derivative(5,1,y)
produces:
Result =
50
Note —
Check = diff(y)
CheckTest = Check(values)
produces:
CheckTest =
40
I will let you troubleshoot that discrepancy.
  댓글 수: 6
lilo moutila
lilo moutila 2021년 1월 9일
So the code should be like this:
syms x y(x)
y(x) = 5*(x^2);
values = 4;
h = 1;
derivative(5,1)
function yd = derivative(values, h, y)
yd = (y(values + h) - y(values - h)) / (2*h);
end
If yes, I still got the error message
Thank you for your help
Star Strider
Star Strider 2021년 1월 9일
I am not getting any error messages when I run the code I posted.
You need to include ‘y’ as an argument in your call to it. Currently, you are not doing that. See my original Answer in order to unbderstand how to do that correctly.
Other than that, I have no idea what the problem is with your implementation of it.

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

카테고리

Help CenterFile Exchange에서 Number Theory에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by