MATLAB: The following error occurred converting from sym to double: Unable to convert expression into double array.”

diff()doubleMATLABsymbolic

When I run my code, I keep getting this error: "The following error occurred converting from sym to double: Unable to convert expression into double array."
I am not an expert at Matlab. Does anyone know what has caused this?
CODE
function [F,U] = Force4(q,Pars)
syms x y x1 y1 x2 y2
q=[x;y];
Pars.q1=[x1;y1];
Pars.q2=[x2;y2];
r1=norm(q-Pars.q1);
r2=norm(q-Pars.q2);
U= -Pars.gamma/r1 - Pars.gamma/r2;
F= -1*[diff(U,x), diff(U,y)]';
U=subs(U,{x;y},{q(1);q(2)});
F=subs(F,{x;y},{q(1);q(2)});

Best Answer

There are few things that does not add up to me in your function:
First, you pass q as input argument and then you assign it to symbolic variables inside the function. Then, you do not need to pass q as an input argument.
Second, you also set gamma to Pars' field value but then you overwrite it again. Don't do it if it is dependent on the input.
Run the following code:
Pars=struct('q1', [-1;0],'q2', [1;0],'gamma',1); %random values for fields, you can change them
[F,U]=Force4(Pars)
Before running the code above, change your function to:
function [F,U]=Force4(Pars)
q1 = Pars.q1; q2 = Pars.q2; gamma = Pars.gamma;
syms x y x1 y1 x2 y2
q=[x;y];
Pars.q1=[x1;y1];
Pars.q2=[x2;y2];
r1=norm(q-q1);
r2=norm(q-q2);
%x=subs(x);
%y=subs(x);
U= -gamma/r1 - gamma/r2;
F= -1*[diff(U,x), diff(U,y)]';
U=subs(U,{x;y},{q(1);q(2)});
F=subs(F,{x;y},{q(1);q(2)});
end
Your function works without any error for me.