user6052232
user6052232

Reputation: 169

Speeding up solving equation with symbolic expression

I am trying to solve an equation using a symbolic (syms) expression, then evaluating it expression using eval. The program is working fine, but it takes a long time. I know using syms decreases the speed, is there any way that I can speed up the process? I was wondering about using a function to put the symbolic expression inside it then calling this function. I do not know if that would help or how to do it though. Any other suggestions are very appreciated.

I used the below code

clear;
clc;
syms A B C D E ; 
R=((4*B*A)/((D-C)^2+(B+A)^2));
R1=((4*B*A)/((D+C)^2+(B+A)^2));
F1 = ellipticK(R);
I1 = ellipticE(R);
F2 = ellipticK(R1);
I2 = ellipticE(R1);
P= ((((A*B)^(1/2))/(2*E*(R^(1/2))))*(((2 - R)*F1) -...
    (2*I1)))-(((((A*B)^(1/2))/(2*E*(R1^(1/2)))))* ...
    (((2 - R1)*F2) - (2*I2)));
P1=feval(symengine,'simplify',P,'IgnoreAnalyticConstraints');

X=(1/B)*(diff(P1,D));
X1=feval(symengine,'simplify',X,'IgnoreAnalyticConstraints');
M(:)=0;
for i=1:10000
    A=L1(i);B=L2(i);C=L3(i);D=L4(i);E=L5(i);
    M(i) = (eval(X1))*0.13; 
end

Upvotes: 0

Views: 91

Answers (1)

m7913d
m7913d

Reputation: 11064

You can transform your problem first to a function handle using matlabFunction as follows:

F = matlabFunction(X1);
M = F(L1, L2, L3, L4, L5)*0.13;

This makes your code ~100x faster.

Note that you can also export your function to a script file, using the 'File' argument:

matlabFunction(f,'File','myFunction.m')

Upvotes: 1

Related Questions