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.
23 ビュー (過去 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 で Mathematics and Optimization についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!