Optimizing program to get faster results
2 views (last 30 days)
Show older comments
Hello;
I am trying to solve equation using (syms) then evaluating the result. The program is working. However, each loop taking almost 27 second. Is there anyway that I can optimize program so it will work faster?
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');
[B,D]= meshgrid(linspace(0.1,10),linspace(0.1,10));
E=3;
N1 = 10*rand(100000,1);
N2 = 5*rand(100000,1);
M(:)=0;
for i=1:100000
tic
A=N1(i);C=N2(i);
F = matlabFunction(X1);
B = F(A, B, C, D, E);
In(:,:,i)=B(:,:);
fprintf('%d\n ', i);
toc
end
6 Comments
Karan Gill
on 10 Jun 2017
- Why do you define B D E as symbolic and then redefine them as numbers/arrays?
- Why use "feval" instead of directly using the "simplify" function?
- Instead of calling a matlab function 100,000 times, can you instead try using "subs" to substitute the arrays in?
Answers (1)
Karan Gill
on 14 Jun 2017
Following up on my comment above:
1. Do not overwrite symbolic variables with numeric values. So don't do
syms B D
and then
[B,D]= meshgrid(linspace(0.1,10),linspace(0.1,10));
Call B and D something else when you initialize the numeric values.
2. Use "simplify" directly. See the documentation for it.
3. Instead of using a loop, use "subs" to substitute an array for the symbolic variable. Again, see the doc for "subs".
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!