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.

21 visualizaciones (últimos 30 días)
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);

Respuesta aceptada

Jan
Jan el 30 de Sept. de 2021
Editada: Jan el 30 de Sept. de 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 comentarios
Nathan Lawira
Nathan Lawira el 30 de Sept. de 2021
Editada: Nathan Lawira el 30 de Sept. de 2021
Oh, I see. It finally works! Thank you so much! What does the command diff() do?
Jan
Jan el 30 de Sept. de 2021
Editada: Jan el 3 de Oct. de 2021
It calculates the difference of neighboring elements. See:
doc diff

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by