Numerical differentiation for function including vector
Afficher commentaires plus anciens
I have implemented a numerical differentiation with central differences. I differentiate the function with respect to a. This appears to be relatively simple for functions containing scalars, e.g.,
. However, once the function also contains a vector, e.g.,
, where c is a 3 by 1 vector, I am struggling to implement this.
, where c is a 3 by 1 vector, I am struggling to implement this.Below I share my code:
rng default
b = randn(1);
c = randn(3, 1);
f1 = @(a) a^4 * b^3;
%f2 = @(a) (a^4 * b^3 * c.').';
a = 1;
k = 3; % no. derivative
h = 0.1; % step size
cent_diff = zeros(k+1,1);
for i = 0:k
cent_diff(i+1, 1) = sum((-1)^i*nchoosek(k,i)*f1(a+(k/2-i)*h));
end
cent_diff = sum(cent_diff)/h^k;
cent_diff = 3.7304
% check result with symbolic differentiation
syms a
f1 = a^4 * b^3;
diff_3 = diff(f1, a, 3);
a = 1;
vpa(subs(d3)) = 3.7304
The differentiation of f2 can be easily achieved using the symbolic approach. How can I get the corresponding result using finite differences?
2 commentaires
Walter Roberson
le 7 Juin 2021
cent_diff(i+1, 1) = sum((-1)^i*nchoosek(k,i)*f1(a+(k/2-i)*h));
What is the sum over? k i h are scalar. f1 returns a scalar for scalar input.
If you were looking ahead to the case where f1 might return a vector, then you would not want to sum over that vector.
M R
le 7 Juin 2021
Réponse acceptée
Plus de réponses (1)
Sulaymon Eshkabilov
le 7 Juin 2021
0 votes
These answer discussions provide appropriate points how to apply the finite difference method:
1 commentaire
M R
le 7 Juin 2021
Catégories
En savoir plus sur Symbolic Math Toolbox dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!