How can I make this code more efficient?

1 visualización (últimos 30 días)
Mahdi
Mahdi el 14 de Dic. de 2015
Editada: sam0037 el 22 de Dic. de 2015
Hello,
Because of the large number of differential equations I'm trying to solve, I would like to make this code more efficient. I'm using for loops and I think there might be a more efficient way to approach this problem, but I ran out of ideas.
clear all
global kc n
kc=0.0156
t_final=4000; %Input final time for calculations [s]
% Define time range of interest
t_span=[0 t_final] ; % Time span (unit depends on kC and Mi)
% Define number of Mi; number of coalescence
n=1e5; % Number of Mi (i numbers)
M1=4.473e5; % Initial concentration at M1
Mi=[M1 ones(1,n-1).*1e-5]; % Matrix to combine initial conditions (Assume zero everywhere other than M1)
options = odeset('RelTol',1e-14);
[t_solution, Mi]=ode113(@Coalescence_Function_Reaction3, t_span, Mi, options);
and the function is
function dM = Coalescence_Function_Reaction3(t,M)
global kc n
for i=1:n
summation_1=sum(M(1:n)); % The first summation
%summation_2
summation_2=0;
for k=1:i-1
summation_2=summation_2+M(k).*M(i-k);
end
dM(i)=-kc.*summation_1.*M(i)+1/2.*kc.*M(i).^2+1/2.*kc.*summation_2;
end
dM=dM';
end
I need to run this for a large number of n's (>1e5) because my total final concentration is not equaling my initial concentration. (In other words, M1=/=total of Mi at t_final) Please let me know if you have any suggestions and thank you.

Respuesta aceptada

sam0037
sam0037 el 22 de Dic. de 2015
Editada: sam0037 el 22 de Dic. de 2015
Hi,
A good approach to study the performance of the above code would be to use a profiler. The profiler would expose the computationally expensive areas of the code. One can then concentrate on these areas to further improve the performance of the code.
To profile this code use the 'Run and Time' button in the Editor tab. I have used the value of 'n' as 1000 here. On profiling I observed that the inner loop 'k' is most expensive computationally. On vectorizing this, I observed a significant improvement in the performance. Check the attached codes for the illustration. I observed the code to execute seven times faster at my end due to this modification.
Refer to the following MATLAB documentation links to learn more about Measuring and Improving performance of your code:
Further to improve the performance of the code, one can parallelize the code using PARFOR. However, to use PARFOR you would need a Parallel Computing Toolbox.
Refer to the following MATLAB documentation links to learn more about PARFOR function:
Refer to the following MATLAB documentation links to learn more about Parallel Computing Toolbox:

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by