"Themis " <thkountouris@hotmail.com> wrote in message <gokp55$ol8$1@fred.mathworks.com>...
> Hi everyone, i was wondering if someone can help me by finding a way to improve performance on the following function. I shall try to explain as best as I can the equation im trying to implement and then provide my current code.
>
> I am trying to calculate the following sum
> 1/sqrt(N) * SUM(n=1 to n=N) [ cos( (n^k)*(m/M) ]
> m takes value from 1 to M
> M and N are the inputs
>
> I need to calculate the above sum for all values of m
>
> My code is as follows:
>
> function [e] = new5(M,N)
>
> tic;
>
> k=3;
> n=(1:1:N);
> d=zeros(1,M1);
> b=zeros(1,M1);
>
> for m=1:1:M1;
> d=m./M;
> b=cos((n.^k)*d);
> e(m)=(sum(b)/sqrt(N));
> end
>
> hold on
> %plot histogram of data
> hist(e,100);figure(gcf);
> hold off
> toc;
Two very basic tips:
1) Preallocate the result "e"
2) get evertthing that does mot depend on the loop outside
k=3;
n=(1:1:N);
% b & d are be overwritten !!
% d=zeros(1,M1);
% b=zeros(1,M1);
e = zeros(1,M1) ; % 1) preallocation
% 2) put everything fixed outside loop
d = (1:M1) ./ M ;
npk = (n .^ k)
sqrtN = sqrt(N) ;
for ix = 1: numel(d),
b=cos(npk * d(ix));
e(ix)=(sum(b)/sqrtN);
end
This should speed up things considerably.
hth
Jos
