MATLAB: Difference between “diff(x^2)” and “2*x”

solvesymbolic

Hi, I can't figure out how are the following two situations different:
syms x1 x2 F;
U=x1^2+(x2-F)^2;
solve('diff(U,x1)=0','diff(U,x2)=0','x1,x2')
vs.
solve('2*x1=0','2*(x2-F)=0','x1,x2')
In the first case MATLAB can't find a solution, although it is a simple linear system (the same one as in the second case which works fine). Any ideas? Thank you:)

Best Answer

I think the problem is you are mixing calling methods. When you pass a string to SOLVE, it looks at the string and determines the unknowns with SYMVAR or looks for your extra arguments. On the other hand, if you have an equation that has symbolic variables that are defined in the workspace, then you should not pass a string to SOLVE.
Here are two equivalent ways to solve your problem. Note carefully the differences.
clear all
syms x1 x2 F % In this method we use symbolic variables.
U = x1^2+(x2-F)^2; % And a symbolic expression.
% Note that SOLVE assumes expr is equal to zero...
S = solve(diff(U,x1),diff(U,x2),x1,x2) % NO STRINGS!
Now the other method is to use strings. Here we do not need to define any symbolic variables. This is a different method with different rules.
clear all % NO symbolic variables, we use strings only...
STR1 = 'diff(x1^2+(x2-F)^2,x1)=0'; % These will be evaluated
STR2 = 'diff(x1^2+(x2-F)^2,x2)=0'; % inside SOLVE...
S = solve(STR1,STR2,'x1,x2') % We use strings here.
So you see what is happening in your code. When you define U as a symbolic expression in the workspace you expect SOLVE to see it when looking at your string, but it doesn't. When evaluating:
solve('diff(U,x1)=0','diff(U,x2)=0','x1,x2') % Your code
SOLVE ends up with this:
solve('0=0','0=0','x1,x2') % U is a constant! dU/dv = 0
which returns the same thing your original code did.