필터 지우기
필터 지우기

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 (최근 30일)
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);

채택된 답변

Jan
Jan 2021년 9월 30일
편집: Jan 2021년 9월 30일
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
Nathan Lawira
Nathan Lawira 2021년 9월 30일
편집: Nathan Lawira 2021년 9월 30일
Oh, I see. It finally works! Thank you so much! What does the command diff() do?
Jan
Jan 2021년 9월 30일
편집: Jan 2021년 10월 3일
It calculates the difference of neighboring elements. See:
doc diff

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by