how to convert sym to double?

1 Ansicht (letzte 30 Tage)
Physiker192
Physiker192 am 13 Sep. 2014
Kommentiert: Mischa Kim am 15 Sep. 2014
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.

Akzeptierte Antwort

Mischa Kim
Mischa Kim am 13 Sep. 2014
Bearbeitet: Mischa Kim am 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 Kommentare
Physiker192
Physiker192 am 14 Sep. 2014
well i am indeed sorry to bother you but i didn't get it. i'm not used to work with that type of functions so i am a little bit lost. i used what you gave me but it was useless (i mean i couldn't get any answer)
Mischa Kim
Mischa Kim am 15 Sep. 2014
To start with I'd just run the whole thing from the command window:
  1. Execute mydifffunction2, e.g. with n=3
  2. Run the matlabFunction command
  3. Run my_vectorize. For this you need to have the function (see code above) saved in a dir which is in the MATLAB path
  4. Finally, run fsolve
If this does not get you anywhere, where do you get stuck and why?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by