You are on page 1of 46

ELE595

Software Tools for Engineers

Lecture 4: Applications of MATLAB

!
Applications of MATLAB Lecture 4 – Slide 1

ELE595

Software Tools for Engineers

Lecture 4: Applications of MATLAB

Outline
Simulation with SIMULINK Audio signal processing

Further Reading
MATLAB’s online documentation is available from within MATLAB and on the ELE595 Resources page See SIMULINK: Model-Based and System-Based Design, chapter 1, for an introduction to SIMULINK (available within MATLAB and on the ELE595 resources page)

!
Applications of MATLAB Lecture 4 – Slide 2

ELE595

Software Tools for Engineers

SIMULINK

!
Applications of MATLAB Lecture 4 – Slide 3

ELE595

Software Tools for Engineers

SIMULINK
SIMULINK is an extension to MATLAB It is a software package for modelling, simulating and analysing dynamic systems Supports linear and non-linear systems Supports continuous time, discrete time (sampled), hybrid and multi-rate simulations It enables simulation components to be visualised, combined and replicated to make a complex system For a basic introduction, type simintro at the MATLAB prompt Type simulink to start SIMULINK

!
Applications of MATLAB Lecture 4 – Slide 4

or as they are depicted in text books Doesn’t require formulation of the system in terms of differential or difference equations SIMULINK has a comprehensive block library. and connectors You can also customise and create your own blocks ! Applications of MATLAB Lecture 4 – Slide 5 .ELE595 Software Tools for Engineers SIMULINK GUI SIMULINK provides a graphical user interface for building models as block diagrams. sources. containing sinks. using click-and-drag mouse operations It is easy to draw models as you would with pen and paper. linear and non-linear components.

ELE595 Software Tools for Engineers SIMULINK Library ! Applications of MATLAB Lecture 4 – Slide 6 .

ELE595 Software Tools for Engineers SIMULINK Models ! Applications of MATLAB Lecture 4 – Slide 7 .

ELE595 Software Tools for Engineers SIMULINK Models Building a model Drag and drop blocks from SIMULINK libraries Connect them by clicking and dragging their connection ports Save and load as .mdl (model) files Running the model Double click on the blocks to set their parameters (e.g. initial conditions) Select Configuration Parameters from the Simulation menu to set up the parameters for the simulation Select Start from the Simulation menu to run the simulation ! Applications of MATLAB Lecture 4 – Slide 8 .

and then double-click on blocks to go down through the levels to see increasing levels of model detail This helps to manage complexity of larger systems and provides insight into the organisation of a model and how its parts interact ! Applications of MATLAB Lecture 4 – Slide 9 .ELE595 Software Tools for Engineers SIMULINK Models SIMULINK models are hierarchical Models can be built with either a top-down or bottom-up approach You can view the system at a high level.

ELE595 Software Tools for Engineers Simulation Interactive and batch processing Use SIMULINK menus for interactive work Use MATLAB’s command window or write a script for batch simulations Visualisation Scopes and other display blocks are available for seeing the simulation results while the simulation is running Change parameters interactively for what-if analysis Results can be put in the MATLAB workspace for post-processing and further visualisation MATLAB and SIMULINK are well integrated so that it is easy to switch between them ! Applications of MATLAB Lecture 4 – Slide 10 .

sec/m ! Applications of MATLAB Lecture 4 – Slide 11 .e. wheel friction. F = −bv The total force on the car is: F − bv Newton’s 2nd law: M dv dt = F − bv Assume F = 400N. etc.ELE595 Software Tools for Engineers Car Motion Example Consider a car which has an engine which provides a constant force F (not very realistic!) The car has mass M v is the horizontal velocity of the car The car experiences a damping force which is proportional to its velocity (due to wind resistance. i.) The damping coefficient is b. b = 40N. M = 1000kg.

ELE595 Software Tools for Engineers Car Motion Example ! Applications of MATLAB Lecture 4 – Slide 12 .

the string is represented by a digital delay line.ELE595 Software Tools for Engineers Plucked String Example In 1983.g. guitar. harp) A more general version of their method is called digital waveguide synthesis. implemented as a circular buffer The buffer is initialised with random values (simulates the initial conditions from plucking the string) ! Applications of MATLAB Lecture 4 – Slide 13 . which was released in commercial synthesisers in the 1990’s by Yamaha In the Karplus-Strong method. Karplus and Strong published a very simple model for synthesising the sound of plucked strings (e.

ELE595 Software Tools for Engineers Plucked Strings The vibration of the string is almost periodic The pattern of vibrations repeats every period The length of the pattern determines the pitch of the sound (longer patterns give lower pitch) The string gradually loses energy. by averaging each successive pair of values ! Applications of MATLAB Lecture 4 – Slide 14 . due to: Transmission of energy through the bridge to the soundboard Friction within the string Friction between the string and the air The energy losses are greater for higher frequencies This can be simulated by a simple low-pass filter.

ELE595 Software Tools for Engineers Karplus-Strong Model ! Applications of MATLAB Lecture 4 – Slide 15 .

ELE595 Software Tools for Engineers Karplus-Strong Model The switch initially passes the values from the random number generator When the counter reaches 170. which can then be stored as a WAV file or played back ! Applications of MATLAB Lecture 4 – Slide 16 . the switch changes state to pass the values from the feedback loop The 169-point delay holds the "state" of the string The values coming out of the delay are averaged with the previous value and fed back via the switch into the delay loop These values are also sent to the output.

ELE595 Software Tools for Engineers Karplus-Strong Output Output of this model: ! Applications of MATLAB Lecture 4 – Slide 17 .

ELE595 Software Tools for Engineers Audio Processing in MATLAB ! Applications of MATLAB Lecture 4 – Slide 18 .

ELE595 Software Tools for Engineers Basics of Digital Audio Sound travels in air via small variations in air pressure which are transmitted as longitudinal waves This audio signal can be converted into a digital signal by sampling the wave at regular intervals in time ! Applications of MATLAB Lecture 4 – Slide 19 .

WAV file on your computer The Sampling Theorem states that frequencies up to half of the sampling rate can be represented in a digital signal An audio CD has: Two independent channels of audio data A sampling rate of 44100 Hz (samples per second) Each sample represented as a 16-bit integer (values from -32768 to 32767) This is considered good quality for consumer audio devices ! Applications of MATLAB Lecture 4 – Slide 20 .ELE595 Software Tools for Engineers Basics of Digital Audio Such sequences of samples are what make up audio files such as on a CD or in a .

FILENAME).g. Audio signals can be written to a WAV file using: % wavwrite(AUDIO. ’whitenoise. 44100. Or they can be played to the sound card using: % sound(AUDIO. a "white noise" audio signal can be created from a sequence of random values: y = rand(44100. 44100). SAMPLE_RATE). sound(y. % assuming abs(y) <= 1 ! Applications of MATLAB Lecture 4 – Slide 21 . SAMPLE_RATE.1)*2-1.ELE595 Software Tools for Engineers Audio in MATLAB In MATLAB. wavwrite(y. audio signals are scaled to have values between -1 and 1 E.wav’).

ELE595 Software Tools for Engineers Loudness of Audio Signals The magnitude of the values in the audio signal is related to its perceived intensity or loudness Loudness is measured as an average over time Usually the root mean square (RMS) amplitude is calculated Loudness is usually measured on a logarithmic scale (in deciBels.wav’). dB).^ 2)). % Calculate RMS amplitude: rms = sqrt(mean(y . % Convert to logarithmic (decibel) scale: dB = 20 * log10(rms). Applications of MATLAB Lecture 4 – Slide 22 ! . relative to the absolute threshold of hearing (values go up from 0dB) or to the maximum possible level given the audio format (values go down from 0 dB) y = wavread(’sound.

freq = (0:1024) * sampleRate / 2048. spectrum(1:bands)).wav’). plot(freq(1:bands). ! Applications of MATLAB Lecture 4 – Slide 23 . bands = 1025.ELE595 Software Tools for Engineers Frequency of Audio Signals The frequencies where a signal has energy are related to the pitch and tone colour of the sounds The amount of power at each frequency (the power spectrum) can be calculated using the (fast) Fourier Transform (FFT) [y sampleRate] = wavread(’pianoTone.^ 2. spectrum = abs(fft(y)) .

data contains repeating patterns which are best analysed in the frequency domain The Fourier transform breaks down a periodic signal into a sum of sinusoids. where the frequencies of the sinusoids are integer multiples of some fundamental frequency If the period (length of the FFT) is T .ELE595 Software Tools for Engineers Spectral Analysis In many engineering applications. the Fourier transform estimates the magnitude and phase of that component of the signal This can be expressed in rectangular coordinates (using complex numbers) or polar coordinates The MATLAB fft function computes the Fourier transform very efficiently ! Applications of MATLAB Lecture 4 – Slide 24 . then the fundamental 1 frequency F = T For each frequency.

unless otherwise specified by DIM If N is given and non-empty. DIM) computes the fast Fourier transform (FFT) of DATA The FFT is computed along the first non-singular dimension of the matrix DATA. it is expanded to length N and padded with zeros The result is an array or matrix of complex numbers ! Applications of MATLAB Lecture 4 – Slide 25 .ELE595 Software Tools for Engineers fft fft(DATA. it defines the number of elements of DATA to use in the FFT If N is smaller than the length of DATA. it is truncated If N is larger than the length of DATA. N.

0.5 * sin(400*pi*t). plot(freq. % sampling rate 1kHz y = sin(100*pi*t) + 2 * cos(300*pi*t) + . s = fft(y). 3 peaks are visible: 1st at frequency 50Hz 2nd at frequency 150Hz 3rd at frequency 200Hz Some leakage is visible not pure impulses ! Applications of MATLAB Lecture 4 – Slide 26 .. freq = (0:2048) * 1000 / 4096. abs(s(1:2049)))..ELE595 Software Tools for Engineers Example: fft – artificial data t = (0:4095)/1000.

1324.201:4296)). 1055.1kHz s = fft(y(1.. 1594.ELE595 Software Tools for Engineers Example: fft . Several peaks are seen: Fundamental ˜269Hz Harmonics at 528. % 2 channels. abs(s(1:500))/1e6).wav’). sampling rate 44. freq = (0:2048) * 44100 / 4096. plot(freq(1:500). . Hz Harm. 797..real data y = wavread(’pianoTone. spacing ˜265Hz Note is middle C (262Hz) Leakage & noise are visible not pure impulses Applications of MATLAB Lecture 4 – Slide 27 ! .

.ELE595 Software Tools for Engineers Periodic Signals If an audio signal consists of a repeating sequence of values it is said to be periodic Sine and cosine are examples of periodic functions Fourier’s Theorem states that any periodic signal can be expressed as a sum of sinusoidal signals. perfectly periodic signals sound unnatural ! Applications of MATLAB Lecture 4 – Slide 28 . where: 1 The fundamental frequency is one over the period (f1 = T ) The frequencies of the sinusoids are integer multiples of the fundamental frequency (fk = kf1 ) Musical notes are examples of approximately periodic signals The fundamental frequency determines the pitch But ..

^ ((0:87)/12)).g. the fundamental frequencies of the notes range from 27. on a piano. >> pianoFreq(40) % "Middle C" ans = 261.63 ! Applications of MATLAB Lecture 4 – Slide 29 .ELE595 Software Tools for Engineers Musical Pitch Musical notes are (approximately) periodic Most of their energy is at integer multiples of the fundamental frequency Higher pitches correspond to higher frequencies and shorter periods (and vice-versa) E.5 * (2 .5 Hz (A0) to 4186 Hz (C8) Each note has a frequency of 21/12 times the next lower note >> pianoFreq = 27.

peaks are approximately at multiples of 262Hz Applications of MATLAB Lecture 4 – Slide 30 ! .ELE595 Software Tools for Engineers Example: Piano Spectrum Piano spectrum: most of the power is concentrated at low frequencies A close-up showing the relative magnitude of the first 9 partials.

ELE595 Software Tools for Engineers Example: Piano Spectrum Human hearing has an approximately logarithmic response to magnitude The log-magnitude spectrum makes the low-power parts of the signal visible: ! Applications of MATLAB Lecture 4 – Slide 31 .

ELE595 Software Tools for Engineers White Noise Waveform of white noise (random values) Spectrum of white noise (energy is spread across all frequencies) ! Applications of MATLAB Lecture 4 – Slide 32 .

bands = 1025. 1).M.N): make M-by-N copies of A y = repmat(rand(100.1)*2-1. figure(2). freq = (0:1024) * 44100 / 2048. plot(freq(1:bands). spectrum(1:bands)).^ 2. ! Applications of MATLAB Lecture 4 – Slide 33 . plot(y). spectrum = abs(fft(y(1:2048))) .ELE595 Software Tools for Engineers Periodic Noise We can make a periodic function out of noise by taking a random sequence and repeating it indefinitely % repmat(A. 441.

ELE595 Software Tools for Engineers Periodic Noise Waveform of periodic noise – a repeating pattern Spectrum of periodic noise – energy occurs only at multiples of the fundamental frequency Applications of MATLAB Lecture 4 – Slide 34 ! .

. as shown in the spectrum ! Applications of MATLAB Lecture 4 – Slide 35 . all energy occurs at integer multiples of F: N = 100 samples R = 44100 Hertz F = R / N = 441 Hertz Energy is nonzero at 441 Hz. the period is T = N / R The fundamental frequency is F = 1 / T = R / N For a periodic wave with fundamental frequency F. etc.ELE595 Software Tools for Engineers Periodic Noise Example y contains a random pattern of 100 numbers which is repeated 441 times to make 1 second of sound If the sampling rate is R = 44100 Hz and the length of one period is N samples. 882 Hz. 1323 Hz.

sound(a110. 1). Periodic noise at 110 Hz a110 = repmat(rand(400. 1).1)*2-1. sound(a55. 1). sound(a220. Periodic noise at 55 Hz a55 = repmat(rand(800. 44100).1)*2-1.ELE595 Software Tools for Engineers Periodic Noise Examples Periodic noise at 441 Hz a441 = repmat(rand(100. sound(a441. 441. 44100). 1). 220.1)*2-1. 44100). the fundamental frequency is halved and the sound is one octave lower Applications of MATLAB Lecture 4 – Slide 36 ! .1)*2-1. Periodic noise at 220 Hz a220 = repmat(rand(200. Each time the period is doubled. 44100). 55. 110.

ELE595 Software Tools for Engineers Timbre (Tone Colour) Timbre (tone colour) is what makes instruments playing the same note sound different Determined by the amount of power at each harmonic (multiple of the fundamental frequency) The spectra of natural sounds are not constant. but change over time Often it is useful to visualise the way the spectral content of a signal changes over time A waterfall plot is a 3-dimensional representation of magnitude plotted against time and frequency A spectrogram uses colour instead of a 3rd dimension to plot magnitude against time and frequency These are also useful to find when sounds start and end ! Applications of MATLAB Lecture 4 – Slide 37 .

ELE595 Software Tools for Engineers Waterfall Plot ! Applications of MATLAB Lecture 4 – Slide 38 .

ELE595 Software Tools for Engineers Spectrogram ! Applications of MATLAB Lecture 4 – Slide 39 .

square waves) can be created by summing sinusoids ! Applications of MATLAB Lecture 4 – Slide 40 .g. len) % Returns a sinusoidal tone with % fundamental frequency ’freq’. triangle. sawtooth.ELE595 Software Tools for Engineers Sound Synthesis in MATLAB MATLAB can be used for synthesising sounds The simplest waveform is the sine wave: function snd = sinetone(freq. x = 2 * pi * freq * (0:len-1) / sr. Other waveforms (e. sampling % rate ’sr’. and length ’len’ (in seconds) len = round(len * sr). snd = sin(x). sr.

sinetone(piano(note). rate = 44100.wav’).rate.5 * (2 .ELE595 Software Tools for Engineers A Test Scale We can play a scale by concatenating individual notes The following code creates an A major scale.3 seconds piano = 27.dur)].^ ((0:87)/12)). end wavwrite(snd. dur = 0. for note = startNote + majorScale snd = [snd. Applications of MATLAB Lecture 4 – Slide 41 ! . snd = []. startNote = 37. % A3 majorScale = [0 2 4 5 7 9 11 12]. rate.3. with each note lasting 0. ’sin-Amaj.

ELE595 Software Tools for Engineers Complex Tone Synthesis More complex waveforms can be synthesised. sr. a sawtooth wav: function snd = sawtoothtone(freq. snd = zeros(1. len) % Returns a sawtooth wave tone with % fundamental frequency ’freq’. e.len). x = (0:len-1) * 2 * pi * freq / sr. and length ’len’ (in seconds) len = round(len * sr).g. sampling % rate ’sr’. for i=1:10 snd = snd + sin(i*x) / i. end ! Applications of MATLAB Lecture 4 – Slide 42 .

sr. and length ’len’ (in seconds) len = round(len * sr). x = (0:len-1) * 2 * pi * freq / sr.ELE595 Software Tools for Engineers Complex Tone Synthesis A square wave consists of frequencies which are odd multiples of the fundamental frequency: function snd = squaretone(freq.len). sampling % rate ’sr’. snd = zeros(1. len) % Returns a square wave tone with % fundamental frequency ’freq’. end ! Applications of MATLAB Lecture 4 – Slide 43 . for i=1:2:20 snd = snd + sin(i*x) / i.

len). len) % Returns a triangle wave tone with % fundamental frequency ’freq’. (-1)^((i-1)/2) * . end Applications of MATLAB Lecture 4 – Slide 44 ! . sr. for i=1:2:20 snd = snd + . and length ’len’ (in seconds) len = round(len * sr). x = (0:len-1) * 2 * pi * freq / sr. sin(i * x) / i^2... but with different ratios and phases: function snd = triangletone(freq.ELE595 Software Tools for Engineers Complex Tone Synthesis A triangle wave also consists only of odd harmonics. snd = zeros(1.. sampling % rate ’sr’..

ELE595 Software Tools for Engineers Plucked String Synthesis Algorithms such as the Karplus-Strong algorithm can also be implemented directly in MATLAB function snd = karplusStrong(freq. snd = zeros(len. y(1:end-1)]) / 2.1)*2-1. end Applications of MATLAB Lecture 4 – Slide 45 ! . sampling % rate ’sr’. y = rand(period. and length ’len’ (in seconds) len = round(len * sr).1) = y. sr. period = round(sr / freq). y = (y + [y(end).1). len) % Returns a plucked string sound with % fundamental frequency ’freq’. for i = 0 : period : len-period snd(i+1:i+period.

ELE595 Software Tools for Engineers High Quality Synthesis Obviously the approaches we cover in ELE595 are extremely simple. so we should not expect high quality results Two main methods of achieving high quality synthesis: Sampling synthesis: digital recordings of individual notes are stored in the synthesiser and played back when required (optionally with some processing of the sound) Physical modelling synthesis: the synthesiser runs a computer simulation of the instrument and how it responds to input from the user Most commercial synthesisers use sampling The most impressive results come from physical modelling: ! Applications of MATLAB Lecture 4 – Slide 46 .