# how to convert sym to double?

조회 수: 6 (최근 30일)
Physiker192 2014년 9월 13일
댓글: Mischa Kim 2014년 9월 15일
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.

댓글을 달려면 로그인하십시오.

### 채택된 답변

Mischa Kim 2014년 9월 13일
편집: Mischa Kim 2014년 9월 15일
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없음 표시없음 숨기기
Physiker192 2014년 9월 14일
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 2014년 9월 15일
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?

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Numeric Solvers에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by