Effacer les filtres
Effacer les filtres

I need to make a function that solves the first derivative of a function using forward finite difference. I've tried creating the function but I encountered an error.

4 vues (au cours des 30 derniers jours)
I tried doing:
function f = q3func(x)
f=(x.^3)-(x.*2)+4;
end
function [firstderivative] = forwarddiff(func,inter,stepsize)
%Finding the first derivative of a function through forward differentiation
firstderivative=[];
count=1;
for i=inter(1):stepsize:inter(end)-stepsize;
firstderiv=((func(i+stepsize)-func(i))./stepsize);
firstderivative(count)=firstderiv;
count=count+1;
end
[fd]=forwarddiff('q3func',[-2:2],0.25)
So that I can get the first derivative value at i using forward finite difference. The problem is that I always encounter the error (shown below) whenever I try to run the function. What I want to obtain from func(i+stepsize) is the final calculation of q3func(i+stepsize) because I inputted q3func as the function of interest (i.e. i+stepsize = -1.75 then q3func(i+stepsize) = 2.1406). Is there something flawed about my code?
The error:
Array indices must be positive integers or logical values.
Error in forwarddiff (line 6)
firstderiv=((func(i+stepsize)-func(i))./stepsize);

Réponse acceptée

Jan
Jan le 30 Sep 2021
Modifié(e) : Jan le 30 Sep 2021
You provide the CHAR vector 'q3func' as input, but you want a handle to the function instead:
fd = forwarddiff(@q3func, -2:2, 0.25)
If func is the vector 'q3func', the expression (i+stepsize) is interpreted as index, which must be a positive integer.
Hint: In your loop the function is evaluated twice for all inner points. q3func accepts vectors as inputs. You can obtain the output of the function once only and use diff() to calculate the difference:
function dx = forwarddiff(func, inter, stepsize)
x = inter(1):stepsize:inter(end);
dx = diff(func(x)) ./ stepsize;
end
  2 commentaires
Nathan Lawira
Nathan Lawira le 30 Sep 2021
Modifié(e) : Nathan Lawira le 30 Sep 2021
Oh, I see. It finally works! Thank you so much! What does the command diff() do?
Jan
Jan le 30 Sep 2021
Modifié(e) : Jan le 3 Oct 2021
It calculates the difference of neighboring elements. See:
doc diff

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical 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