Trouble with my function
Ältere Kommentare anzeigen
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.
Antworten (1)
Star Strider
am 9 Jan. 2021
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 Kommentare
lilo moutila
am 9 Jan. 2021
Star Strider
am 9 Jan. 2021
O.K., then do so. I used the anonymous funciton version because it is more convenient for me. The results will be the same.
It will still be necessary to include ‘y’ as an argument, regardless of the function format.
lilo moutila
am 9 Jan. 2021
Star Strider
am 9 Jan. 2021
It must be some version of:
function yd = derivative(values, h, y)
yd = (y(values + h) - y(values - h)) / (2*h);
end
The order of the arguments are not important, so long as the call to ‘derivative’ has them in the same order.
‘And you said that i have to include 'y' as an argument.’
I did, because ‘derivative’ does not otherwise have a definition of ‘y’ (in most instances, however I will not go into the exceptions here), so it must be passed as an argument.
It is also not necessary (and is likely not appropriate) to declare:
syms y(x)
inside ‘derivative’, since it already has been declared (and therefore exists) as a symbolic function.
lilo moutila
am 9 Jan. 2021
Star Strider
am 9 Jan. 2021
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.
Kategorien
Mehr zu Assumptions finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!