How to implement this without using for?

This is my code:
function Y=FCOS(win)
N=size(win,2)-1;
teta=2*pi/N;
d=2*pi/N;
win1=win(:,1:N);
win2=win(:,2:N+1);
C1=0; C2=0;
for j=1:N
C1=C1+(2/N)*win1(:,j)*cos(j*teta);
C2=C2+(2/N)*win2(:,j)*cos(j*teta);
end
Yc=C1;
Ys=(C1*cos(d)-C2)/sin(d);
Y=complex(Yc,Ys);
My idea was to do the following:
C1=2/N*sum(win1.*cos((1:N)*teta),2);
C2=2/N*sum(win2.*cos((1:N)*teta),2);
But it will only work if my variable 'win' has only 1 line. For this to work, I would have to use, instead of (1:N), [1:N; 1:N; 1:N ... ;1:N], where this matrix should have the same number of lines as 'win'. But I can only think of a way of doing this with a for.
Anyone have a better solution?

 Respuesta aceptada

Sean de Wolski
Sean de Wolski el 6 de Mayo de 2011
Close!
Use bsxfun:
C1 = sum(2/N*bsxfun(@times,win1,cos((1:N)*teta)),2);
C2 = sum(2/N*bsxfun(@times,win2,cos((1:N)*teta)),2);
And to make it faster do the cos(1:N)*teta only once:
cosnxteta = cos((1:N)*teta));
C1 = sum(2/N*bsxfun(@times,win1,cosnxteta,2);
C2 = sum(2/N*bsxfun(@times,win2,cosnxteta,2);

3 comentarios

Bernard Küsel
Bernard Küsel el 6 de Mayo de 2011
Thanks! It really sped up the code. I will surely use more of bsxfun for future coding!
Would you know how to create that [1:N; 1:N; 1:N ... ;1:N] matrix without using for?
Sean de Wolski
Sean de Wolski el 6 de Mayo de 2011
repmat(1:N,[ntimes,1]); %But this can often be avoided with bsxfun!
Bernard Küsel
Bernard Küsel el 6 de Mayo de 2011
Thanks for the tips!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by