Optimizing program to get faster results

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

doc profile
is the first place to start. Find out which lines are actually taking the time before you try to optimise anything.
The Matlab profiler is very easy and intuitive to use, unlike some I have used for other languages.
@ Adam. Than you.
B = F(A, B, C, D, E); This line and each Loop are taking around 27 sec
Well, if you click on that in the profiler you should be able to drill down further into that. I don;t use the symbolic toolbox so I don't really know what a lot of this code is doing or what
matlabFunction
is supposed to be - it sounds a ridiculously generic name. Is it a builtin function and is it returning a function handle?
Stephen23
Stephen23 on 9 Jun 2017
Edited: Stephen23 on 9 Jun 2017
@Adam: matlabFunction converts a symbolic expression into a MATLAB function handle.
  • 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?
Thank you.
- I define it as as symbols because this is part of the program. I use it in the next line to find the derivative (X=(1/B)*(diff(P1,D));).
- For the second and third part, I do not know how to do it. I hope if you can help me to do it

Sign in to comment.

Answers (1)

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".

Categories

Asked:

on 9 Jun 2017

Answered:

on 14 Jun 2017

Community Treasure Hunt

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

Start Hunting!