# How do i make my code faster?

2 views (last 30 days)
Jelthe on 21 Apr 2016
Commented: Brendan Hamm on 21 Apr 2016
Hello,
so i´ve written a code for creating random spectra. It will compute a random spectra between -pi and pi. After one fouriertransformation, a gaussianfilter and one backtransformation i got a 700 x 1 double as my spectra i need. So this basicly works fine. Now i want to have like 9000 times this 700 x 1 spectra in one structure. I made a while loop and a counter to fill every row of the struct with a new created spectra on every new loop. BUT of course it takes like, i assume, an hour to make 9000 of these 700x1 spectra. How can i make my code faster? I think its because matlab has to reread the struct wich is growing with every loop. Is there any good solution to avoid this? enclosed my Code (iam new to matlab, sorry for bad programming):
Sorry for this Big question.
% Defining Number of Spectra/Event
No_event=700;
No_spectra=10;
% Defining Guassfilter parameter
offset=350;
width=50;
Amplitude=5;
% Defining spectra y-value
randPosPi=-pi;
randNegPi= pi;
% Predefining struct
k=zeros(1,No_event);
a=1:No_spectra;
c=cell(size(a'));
field = 'spectra';
struct = struct(field,c);
[struct.spectra]=deal(k');
r = 0;
% Guassianfilter
x=1:No_event;
l(x)=Amplitude*exp((-(x-offset).^2)/((2*width)^2));
lstr=l';
% Computing Spectra
while r <= No_spectra
for spectra=1:No_spectra
% generating random numbers between -pi and pi
randomPi = randPosPi + (randNegPi-randPosPi).*rand(No_event,1); %random numbers between -pi and pi
% Fouriertransformation
fourier_of_randomPi=fft(randomPi);
Pi_gauss=lstr.*fourier_of_randomPi; %guass multiplied with fft of random Pi
%Pi_gauss_real=lstr.*realteil;
% Backtransformation
backfft_randomPi=fft(Pi_gauss);
Spektrum=lstr.*abs(real(backfft_randomPi));
% inserting double data from Spektrum into struct
struct(1+r).spectra=deal(Spektrum);
end
r=r+1;
if r==(No_spectra);
break
end
end
Brendan Hamm on 21 Apr 2016
Is there any need to have a struct? You could just store all this data in a pre-allocated matrix.

Jan on 21 Apr 2016
Edited: Jan on 21 Apr 2016
If you want to improve the speed of code, find the bottleneck at first. It is useless to improve a part of the code, which uses 0.5% of the total time only. The profiler is the tool for such investigations. I assume fft is the most demanding part, so your code does not matter. Can you reduce the number of fft calls?
Note: Replace this:
r = 0;
while r <= No_spectra
...
r = r+1;
if r == (No_spectra); % Not require, because <= No_spectra is checked also
break
end
end
by:
for r = 0:No_spectra
...
end
This will not reduce the runtime but it looks nicer and the higher the readability, the easier is the debugging.
This:
struct = struct(field,c);
is a very bad idea, because to shadow the builtin function with a variable. Be sure to use another name.