Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
Momo
Momo le 7 Sep 2017
Modifié(e) : Momo le 13 Fév 2018
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

Réponse acceptée

David Goodmanson
David Goodmanson le 8 Sep 2017
Modifié(e) : David Goodmanson le 8 Sep 2017
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 commentaire
David Goodmanson
David Goodmanson le 8 Sep 2017
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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by