我知道Matlab有内置函数来确定相关的勒让德函数。我想计算勒让德多项式,这是那些特殊情况。我为此任务编写了自己的代码,并与Matlab内置函数进行了比较。这是比较代码:
function op
t1 = zeros(1,100);
t2 = zeros(1,100);
P1 = zeros(1,10);
for m = 1:100
tic;
% It is neccessary a for loop for the first ten terms (m =1,...,10) of
% Legendre polynomial with legendre matlab built-in function
for i = 1:10
A = legendre(i,0);% legendre function determines the associated
% Legendre functions
P1(i) = A(1,1);% Legendre polynomials are the first row of A
end
t1(m) = toc;
tic;
% My own function determines the first ten terms at a time
P2 = legendrep2(0,10);
t2(m) = toc;
end
% Mean time using the Matlab built-in legendre functions
t1_mean = mean(t1),
% Mean time using my own custom legendre polynomial function
t2_mean = mean(t2),
function [Pl] = legendrep2(gamma,fin_suma)
Pl = zeros(1,fin_suma);
Pl(1) = gamma;
Pl(2) = 0.5*(3*gamma*Pl(1)-1);
for j =3:fin_suma;
Pl(j) = ((2*j-1)*gamma*Pl(j-1)-(j-1)*Pl(j-2))/j;
end
end
end
这些是我的结果:
t1_mean =
0.001621042906210
t2_mean =
7.536710452587590e-006
所以,我想知道是否有可能改进我的代码(legendrep2函数)。
答案 0 :(得分:2)
尝试使用Matlab分析器找出瓶颈所在:
菜单 - >桌面 - >概述
这将有助于您专注。