# Help on Improving performance for MATLAB function

• Mar 3rd 2009, 06:30 PM
thankarathan
Help on Improving performance for MATLAB function
Im trying to make my function run faster and I was wondering if anyone can help me. I'm trying to calculate the following equation :
ImageShack - Image Hosting :: 29384513.jpg
where N and M are inputs. Basically i need to caluclate that sum for all values of m.
This is my current code:

function [e] = new5(M,N)

tic;

k=3;
n=(1:1:N);
d=zeros(1,M-1);
b=zeros(1,M-1);

for m=1:1:M-1;
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;

Any ideas?
• Mar 4th 2009, 06:27 AM
CaptainBlack
Quote:

Originally Posted by thankarathan
Im trying to make my function run faster and I was wondering if anyone can help me. I'm trying to calculate the following equation :
ImageShack - Image Hosting :: 29384513.jpg
where N and M are inputs. Basically i need to caluclate that sum for all values of m.
This is my current code:

function [e] = new5(M,N)

tic;

k=3;
n=(1:1:N);
d=zeros(1,M-1);
b=zeros(1,M-1);

for m=1:1:M-1;
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;

Any ideas?

Code:

```N=3;M=4;   tic;   k=3; n=(1:1:N); d=zeros(1,M-1); b=zeros(1,M-1);   n=1:N; m=1:M-1;   d=m/M; theta=n'.^k*d; b=cos(theta); e=sum(b)/sqrt(N);   hold on plot histogram of data hist(e,100);figure(gcf); hold off toc```
CB
• Mar 4th 2009, 08:52 AM
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
• Mar 4th 2009, 10:20 AM
CaptainBlack
Quote:

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