the average rate of change of the function to find the derivative

1 次查看(过去 30 天)
I am trying to write a program to find f'(x)=f(x+h)-f(x)/h at different h
I could not get the result. I do not know where is my mistake could you please help me

采纳的回答

David Goodmanson
David Goodmanson 2017-9-8
编辑:David Goodmanson 2017-9-8
Hello Asma
Take a look at the following
>> 1:8 ans = 1 2 3 4 5 6 7 8
>> -1:-8 ans = 1×0 empty double row vector
>> -1:-1:-8 ans = -1 -2 -3 -4 -5 -6 -7 -8
Matlab assumes by default that indices are incremented by +1. If you want to decrement by -1 you have to supply that information as on the last line. That change gets the for loop going. However, you are not saving the answer for different values of k. Values can be saved in an array z, but indices that address an array must be positive. So it's better to have positive values of k and adjust accordingly.
z = zeros(1,8) % make an initial z array
for k = 1:8
h = 10.^(-k)
z(k) = (exp(1+h) - exp(1))./h
end
disp(z)
There is no need to define a new function for exp since you can just use exp directly.
  1 个评论
David Goodmanson
David Goodmanson 2017-9-8
Hi Asma,
I didn't get back on this quite soon enough. First, in place of disp(z) it's easier to see the results if z is made into a column vector
format long
disp(z')
I think your intention was to take a look at the difference between the approximate derivative and the exact derivative, which is exp(1). This is
format shorte
disp(z'-exp(1))
which does have a numerical problem at h = 1e-8.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by