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);
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!