MATLAB: How to replace For loops

for loopfor loopssum

I wrote an code with a lots of For loops. I want to replace them and to use functions instead.
wich functions do the same actions?
The code:
w0=(2*pi)/2001;
ak1=zeros(1,2001); %initializing the coeffecients array
%calculating Fourier coeffecients
for k=0:1:2000
s=0;
for n1= 1:1:2001
s=a(n1)*exp(-1i*k*w0*(n1-1001))+s;
end
ak1(k+1)=(1/N)*real(s);
end
Thank's for helping ,
Liron

Best Answer

No functions are needed to replace the for loop in your current code. Just matrix operations are enough.
rng(0);
w0=(2*pi)/2001;
a = rand(1,2001); % missing from your posted code

N = 2001;
n1= 1:1:2001;
k=(0:1:2000)';
s = a*exp(-1i*k*w0*(n1-1001)).';
ak1=(1/N)*real(s);
Test if the output is correct
% your code
rng(0);
w0=(2*pi)/2001;
ak1=zeros(1,2001); %initializing the coeffecients array
a = rand(1,2001); % missing from your posted code
N = 2001;
%calculating Fourier coeffecients
for k=0:1:2000
s=0;
for n1= 1:1:2001
s=a(n1)*exp(-1i*k*w0*(n1-1001))+s;
end
ak1(k+1)=(1/N)*real(s);
end
% my code
s = a*exp(-1i*k*w0*(n1-1001)).';
ak2=(1/N)*real(s); % variable name changed to ak2 for comparison
Result:
>> isequal(ak1,ak2)
ans =
logical
1