Numerically derive a continous, non-symbolic function

I have a function defined via
function y = f(x)
% ...
end
. I now want to numerically calculate the value of it's derivative at a given point. As in, what should be in the following function's body?
function y = derivative_of_f(x)
% Calculate derivative of f at position x here
end
Is there any way to do this, without having to implement numerical differentiation myself?

 採用された回答

darova
darova 2019 年 11 月 26 日
編集済み: darova 2019 年 11 月 27 日

0 投票

Derivative is (if you have numerical data)
dy = (y(i)-y(i-1)) / (t(i)-t(i-1));
Maybe diff (if you have a function) ?
syms x
diff(f(x))

8 件のコメント

fi
fi 2019 年 11 月 26 日
My function is not discretized yet, but continuous! This means I would first have to choose a precice enough discretization to use your method. That all is of course possible, but I was wondering whether there is an easier (built-in?) method where I don't have to reinvent the wheel. Kind of like the fzero function to find roots.
darova
darova 2019 年 11 月 26 日
Maybe diff?
syms x
diff(f(x))
fi
fi 2019 年 11 月 26 日
編集済み: fi 2019 年 11 月 26 日
I don't think that will work here, since my function is not symbolic. For example, as soon as a function contains a case switch like this:
function y = f(x)
if (x > 0)
y = x^2;
else
y = x;
end
end
...diff doesn't work anymore, throwing this error: Conversion to logical from sym is not possible.
Also, I don't want the analytical derivative, but just it's numerical approximation for a single given position.
darova
darova 2019 年 11 月 26 日
Another method
dx = 0.001;
dy = (f(x)-f(x+dx))/dx;
fi
fi 2019 年 11 月 27 日
Yeah, that's seems like the easisest way.
I just wanted to know if there is a preferred, maybe built-in way where I don't have to take care of precision. Anyway, thanks alot!
darova
darova 2019 年 11 月 27 日
Can you accept the answer please
fi
fi 2019 年 11 月 27 日
Well, the answer is currently in your comment and there is no accept button for that :(
Could you maybe edit you original answer?
darova
darova 2019 年 11 月 27 日
yes please

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeSymbolic Math Toolbox についてさらに検索

製品

質問済み:

fi
2019 年 11 月 26 日

コメント済み:

2019 年 11 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by