how to convert sym to double?
4 views (last 30 days)
Show older comments
hello, i have a system of n equations which i need to differentiate, so the variables must be symbolic variables, and i stored those equations in an array, my problem is that i want to solve the system using the fsolve but i am not able to convert my symbolic variables to double, so let my code be like that:
function dif = mydifffunction2 (~)
n=input('n=');
h=3;
dif=sym(zeros(1,n));
F=0;
x=sym(zeros(1,n));
for k=1:n
x(k) = sym(sprintf('x%d',k));
end
for i=1:n
D= 0.5;
% V=0;
% b=0;
for j=1:n
if (mod(j,2)==0)
D = D + cos(h*x(j));
else
D = D - cos(h*x(j));
end
end
D=(2*sqrt(2)/(pi*h))*abs(D);
F = F + 1/h*(D^2)
h=h+2;
end
for j=1:n
dif(j)=diff(F,x(j),1);
end
how can i convert each of these variables to double??? Thanks in advance.
0 Comments
Accepted Answer
Mischa Kim
on 13 Sep 2014
Edited: Mischa Kim
on 15 Sep 2014
Physiker, one approach is to convert the symbolic equation into a MATLAB function (handle) and then use fsolve. E.g.
my_dif = mydifffunction2;
and then use
g = matlabFunction(my_dif);
to create the MATLAB function handle, which in turn needs to be converted
h = my_vectorize(g);
to be used in
fsolve(h,[1,1,1]) % e.g. with n = 3
my_vectorize could look something like:
function f_vec = my_vectorize(fun)
f_vec = @fun_vectorize;
function out = fun_vectorize(x)
x = num2cell(x);
out = fun(x{:});
end
end
2 Comments
Mischa Kim
on 15 Sep 2014
To start with I'd just run the whole thing from the command window:
- Execute mydifffunction2, e.g. with n=3
- Run the matlabFunction command
- Run my_vectorize. For this you need to have the function (see code above) saved in a dir which is in the MATLAB path
- Finally, run fsolve
If this does not get you anywhere, where do you get stuck and why?
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!