我试图使用创建的符号向量来区分以下符号表达式,但我一直在收到错误。也就是说,我想要df / dx1,df / dx2和df / dx3。这是我尝试过的:
>> x = sym('x', [3 1])
x =
x1
x2
x3
>> symbolic = 0.5*transpose(x)*eye(1)*x + [1 1 1]*x
symbolic =
x1^2/2 + x1 + x2^2/2 + x2 + x3^2/2 + x3
>> diff(symbolic, x)
Error using mupadmex
Error in MuPAD command: Invalid argument. [contains]
Evaluating: (Dom::Matrix(Dom::ExpressionField()))::_mult1
Error in sym/diff (line 44)
R = mupadmex('symobj::diff', S.s, x.s, int2str(n));
>> diff(symbolic, x.x1)
Error using sym/subsref
Too many output arguments.
非常感谢任何帮助。谢谢!
答案 0 :(得分:2)
您可以尝试以下两个选项之一:
% option 1
x = sym('x', [3 1]);
f = 0.5*transpose(x)*eye(1)*x + [1 1 1]*x;
for i=1:3
Df(1,i) = diff(f, x(i));
end
% I do not like this option because I do not know
% how to evaluate the expressions with numeric values
x(1) = 1;
eval(Df)
我更喜欢“选项2”,因为评估表达式更容易。
% option 2
syms x1 x2 x3 real; % 'real' fixes x1 x2 x3 as real numbers (not complex ones)
x = [x1 x2 x3]'; % '
f = 0.5*transpose(x)*eye(1)*x + [1 1 1]*x;
for i=1:3
eval(['Df(1,i) = diff(f,x',num2str(i),');']);
end
% To eval at a certain value
x1 = 1;
x2 = 2;
x3 = 3;
eval(Df)
我认为eval只有我上面使用的两个函数:
您可以使用eval来评估作为字符串编写的matlab命令,就像您将其编写为普通代码一样。试试看我的意思:
a = 1; %的设置值为1
eval('a = 2'); %将a的值更改为2
eval(['a =',num2str(5)]); %将a的值设置为5;
希望这有帮助,