speed up 'for' loops

Hi,
How can I speed up following 'for' loops? Help me please.
P=200;
N=40000000;
y(1:P)=3;
% a: P X 1 matrix (vector)
% Z: P X 1 matrix (vector)
% x: N X 1 matrix (vector)
%%%%%Loops
y(P+1:N)=0;
for i=P+1:N
for j=1:P
y(i)=y(i)-a(j)*x(i-j);
end
end
for i=1:N
for j=1:P
f(i,j)=Z(j)^(i-1);
end
end
Thanks in advance.

 Respuesta aceptada

Jan
Jan el 7 de Sept. de 2012
Editada: Jan el 7 de Sept. de 2012

0 votos

P = 200;
N = 40000000;
a = rand(P, 1);
Z = rand(P, 1);
x = rand(N, 1);
y(P+1:N) = 0; % This one at first! -> pre-allocation
y(1:P) = 3;
at = transpose(a);
for i=P+1:N
y(i) = y(i) - at * x(i-1:-1:i-P); % Dot-product of vectors => SUM
end
f = ones(P, N);
for i = 2:N
f(:, i) = f(:, i - 1) .* Z;
end
f = transpose(f);

5 comentarios

Azzi Abdelmalek
Azzi Abdelmalek el 7 de Sept. de 2012
Simon change Zt to Z (error typing)
Jan
Jan el 7 de Sept. de 2012
Thanks, Azzi, this is fixed now.
Coo Boo
Coo Boo el 7 de Sept. de 2012
Editada: Coo Boo el 7 de Sept. de 2012
Thanks, but x(i-1:i-P) is an empty matrix, because i-1>i-P.
Jan
Jan el 7 de Sept. de 2012
Editada: Jan el 7 de Sept. de 2012
Thanks, Coo Boo, fixed now. Unfortunately I cannot test it, because I do not have a Matlab version installed on my current computer. But you are cordially invited to debug it.
Coo Boo
Coo Boo el 7 de Sept. de 2012
Thank you very much

Iniciar sesión para comentar.

Más respuestas (1)

Azzi Abdelmalek
Azzi Abdelmalek el 7 de Sept. de 2012

0 votos

for the second loop
c=repmat(Z',N,1)
f=bsxfun(@power,c,[0:N-1]')

4 comentarios

Jan
Jan el 7 de Sept. de 2012
The power operation is surprisingly expensive. See "type vander".
Azzi Abdelmalek
Azzi Abdelmalek el 7 de Sept. de 2012
you are right, your code is faster for N=400000
Elapsed time is 0.489050 seconds.
Elapsed time is 0.757052 seconds. my code
Coo Boo
Coo Boo el 7 de Sept. de 2012
Thank you very much
Matt Fig
Matt Fig el 7 de Sept. de 2012
No need for REPMAT or [].
f = bsxfun(@power,Z.',(0:N-1).');

Iniciar sesión para comentar.

Categorías

Productos

Etiquetas

Preguntada:

el 7 de Sept. de 2012

Community Treasure Hunt

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

Start Hunting!

Translated by