功能差异 [英] Function differentiation

查看:67
本文介绍了功能差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能:

|| x ||是欧几里得距离.

Where ||x|| is an Euclidean distance.

对于给定的n个(变量数),我希望Matlab区分该函数,然后将实数替换为该函数.

For given n (number of variables) I want Matlab to differentiate this function and then substitute real numbers into it.

我真正不知道该怎么做的是:

What I truly don't understand how to do is:

1)如何让Matlab创建所有这些新的n个变量以供以后区分?

1) How let Matlab create all these new n variables for later differentiation?

2)每个变量都是一个维数为d的矢量,即x = [x1,x2,... xd],因此稍后我想针对某些矢量元素(例如针对x1)区分函数,我该怎么办?

2) Each variable is a vector of dimension = d, i.e x=[x1, x2, ... xd], so later I want to differentiate function with respect to certain vector elements, for example with respect to x1, how can I do it?

每个x_i的函数应有所区别,其中i = 1:n

EDIT 1: function should be differentiated at each x_i, where i=1:n

推荐答案

总和的导数是每个元素的导数的总和...因此,我们只需要查找一次导数(您可以执行此操作手动,如果它是一个简单的函数(如您的玩具示例中所示),但是我们通常使用Symbolic Math Toolbox(符号数学工具箱)来执行此操作):

The derivative of a sum, is the sum of the derivatives of each element... so, we need to find the derivative only once (you can do this manually, if it is a simple function like in your toy-example, but we do this the general way, using the Symbolic Math Toolbox):

syms x y z % declaring 3 symolic variables
F = 1/(norm([x,y,z])); % declaring a function
f = diff(F,x) % calculate the derivative with regard to the symbolic variable x

f =-(abs(x)* sign(x))/(abs(x)^ 2 + abs(y)^ 2 + abs(z)^ 2)^(3/2)

f = -(abs(x)*sign(x))/(abs(x)^2 + abs(y)^2 + abs(z)^2)^(3/2)

您现在有不同的选择.您可以使用 subs 评估函数f(只需将数字值分配给xyz并调用subs(f).或者,您可以使用matlabFunction创建(数字)函数句柄(此我更喜欢这样)

you now have different options. You can use subs to evaluate the function f (simply assign numeric values to x,y, and z and call subs(f). Or, you create a (numeric) function handle by using matlabFunction (this is the way, I prefer)

fnc = matlabFunction(f); % convert to matlab function

然后,您只需要对创建的向量求和(嗯,您需要对两个向量元素中的每个向量求和...)

Then, you just need to sum up the vector that you created (well, you need to sum up the sum of each of the two vector elements...)

% create arbitrary vector
n = 10;
x = rand(n+1,3);

% initialize total sum
SumFnc = 0;
% loop through elements
for i = 1:n
    % calculate local sum
    s = x(i,:)+x(i+1,:);
    % call derivative-function + sum up
    SumFnc = SumFnc + fnc(s(1),s(2),s(3));
end

这篇关于功能差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆