Originally Posted by

**thankarathan** Thank you for your reply. Your code does indeed work a lot faster, however since I;m taking large values of N and M, I get an "out of memory" error for values of M,N> 5000

Then you will have to segment the calculation over sub-blocks of M or N and loop over the blocks.

Something like (this is untested by the way, so no guarantees):

Code:

N=3;M=4;
tic;
k=3;
BlockLen=1000;
e=zeros(1,M-1);
m=1:M-1;
for idx=1:1000:N
n=(idx:min(N,idx+BlockLen-1));
d=m/M;
theta=n'.^k*d;
b=cos(theta);
e=e+sum(b)/sqrt(N);
end
hold on
plot histogram of data
hist(e,100);figure(gcf);
hold off
toc

CB