Vectorization the Legendre Polynomial Without loop

4 views (last 30 days)
Hi All,
I would like to speed up this Legendre polynomial code without using loop. It has a significant delay in my associated code
I would like to alwasy keep L as option which can be changed
t=[1/60:1/60:3];
L=221;
P=zeros(L+1,length(t));
P(1,1:length(t)) = 1;
P(2,1:length(t)) = t;
for i = 2:L
P(i+1,:) = -(i-1)./i.*P(i-1)+(2.*i-1)./i.*t.*P(i);
end
The equation for the Legendre polynomial is
where and
PS: I corected the mathematical equation, sorry for the inconvenience
Many thanks in advance

Accepted Answer

Jan
Jan on 14 Feb 2019
Edited: Jan on 14 Feb 2019
Are you sure the the code is working? You calculate the vectors P(i, :) but use the first element only: P(i):
P(i+1,:) = -(i-1)./i.*P(i-1)+(2.*i-1)./i.*t.*P(i);
% I assume you want:
P(i+1,:) = -(i-1)./i.*P(i-1, :)+(2.*i-1)./i.*t.*P(i, :);
% ^ ^
I do not think that this can be vectorized, because the values of P depend on former values. cumsum etc. is not a solution also. So a small simplification only:
t = 1/60:1/60:3; % No square brackets needs
L = 221;
P = zeros(L+1, length(t));
P(1, :) = 1;
P(2, :) = t;
for n = 2:L
P(n+1, :) = (1 - n) / n * P(n - 1, :) + (2 * n - 1) / n * t .* P(n, :);
end
A columnwise processing is faster in general - in my measurements maybe 10%:
t = (1/60:1/60:3).';
L = 221;
P = zeros(length(t), L+1);
P(:, 1) = 1;
P(:, 2) = t;
for n = 2:L
P(:, n+1) = (1 - n) / n * P(:, n - 1) + (2 * n - 1) / n * t .* P(:, n);
end

More Answers (1)

Ahmed
Ahmed on 16 Feb 2019
Thanks Jan for your answer

Categories

Find more on Polynomials in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!