No BSD License  

Highlights from
Numerical Methods for Physics

from Numerical Methods for Physics by Alejandro Garcia
Companion Software

sprfft.m
% sprfft - Program to compute the power spectrum of a  
% coupled mass-spring system.
clear; help sprfft;  % Clear memory and print header
x = input('Enter initial displacement [x1 x2 x3] - ');  
v = [0 0 0];       % Masses are initially at rest
state = [x v];     % Positions and velocities; used by rk4
tau = input('Enter timestep, tau - ');  % (sec)
k_over_m = 1;      % Ratio of spring const. over mass (1/sec^2)
%%%%%%%%%%%%% Main Loop %%%%%%%%%%%%%%
time = 0;
nstep = 256;       % Number of steps in the main loop
nprint = nstep/16; % Number of steps between printing progress
for istep=1:nstep  
  state = rk4(state,time,tau,'sprrk',k_over_m);  % Runge-Kutta
  time = time + tau;    
  xplot(istep,1:3) = state(1:3);   % Record positions for plots
  tplot(istep) = time;             % Record time for plots
  if( rem(istep,nprint) < 1 )
    fprintf('Finished %g out of %g steps\n',istep,nstep);
  end
end
f = (0:(nstep-1))/(tau*nstep);      % Frequency
x1 = xplot(:,1);              % Displacement of mass 1
x1fft = fft(x1);              % Fourier transform of displacement
spect = x1fft .* conj(x1fft); % Power spectrum of displacement
% Build the weight vector for the Hanning window
window = 0.5*(1-cos(2*pi*((1:nstep)-1)/(nstep-1)));  
x1w = x1 .* window';          % Window the data
x1wfft = fft(x1w);            % Fourier transf. (windowed data)
spectw = x1wfft .* conj(x1wfft); % Power spectrum (windowed data)
% Graph the displacements of the masses
ipr = 1:nprint:nstep;
plot(tplot,xplot(:,1),'-',tplot(ipr),xplot(ipr,1),'o',...
     tplot,xplot(:,2),'-.',tplot(ipr),xplot(ipr,2),'+',...
     tplot,xplot(:,3),'--',tplot(ipr),xplot(ipr,3),'*')
title('Displacement of mass 1- o  2- +  3- *');
xlabel('Time'); ylabel('Displacement');
pause;  % Pause between plots; strike any key to continue
semilogy(f(1:(nstep/2)),spect(1:(nstep/2)),'-',...
         f(1:(nstep/2)),spectw(1:(nstep/2)),'--');
title('Power spectrum (dashed is windowed data)');
xlabel('Frequency'); ylabel('Power');

Contact us at files@mathworks.com