0% found this document useful (0 votes)
61 views63 pages

Mat Lab Slides

This document provides an overview of the capabilities of MATLAB for scientific computing and signal analysis. It introduces MATLAB as a software for matrix computation and discusses its basic working modes. The key sections cover getting started with MATLAB, working with numbers, vectors, matrices and figures. It also describes using script files and writing functions for repeated tasks. The document concludes with a section on using MATLAB for signal analysis and processing.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views63 pages

Mat Lab Slides

This document provides an overview of the capabilities of MATLAB for scientific computing and signal analysis. It introduces MATLAB as a software for matrix computation and discusses its basic working modes. The key sections cover getting started with MATLAB, working with numbers, vectors, matrices and figures. It also describes using script files and writing functions for repeated tasks. The document concludes with a section on using MATLAB for signal analysis and processing.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Scientific Computing with MATLAB

UVMSCUVMSC-MTS3

Cyril Lahuec Francesco P. Andriulli

Overview
What is Matlab? Getting started Working with numbers Working with vectors and matrices Using figures Scripts and M-files Signal analysis with Matlab

Overview
What is Matlab? Getting started Working with numbers Working with vectors and matrices Using figures Scripts and M-files Signal analysis with Matlab

What is Matlab? (Matrix (Matrix Laboratory Laboratory) oratory)


Matrix computation software Command interpreter Uses dedicated toolboxes 2 working modes
Blocksets DSP Power system

Toolboxes
Signal processing

Simulink: graphic interface Outputs:


command window graphic windows

Interactive: execute on-line command Executive: execute line by line command files (M-files) Works with interconnected blocks

Simulink graphic interface Graphic windows (outputs) Matlab interpretor

M-files

Control System

Command window

system identification

Overview
What is Matlab? Getting started Working with numbers Working with vectors and matrices Using figures Scripts and M-files Signal analysis with Matlab

Getting started
Start a linux session (use Reflexion X) Create a folder from which you will kick off Matlab
Case sensitive!!!!

Type in SETUP CLASSROOM2012b Type in matlab &

Environment (I)

Variables being used

Command window Command history

Start menus: Simulink

Environment (II).

Overview
What is Matlab? Getting started Working with numbers Working with vectors and matrices Using figures Scripts and M-files Signal analysis with Matlab

Working with numbers(I)

^ : exponentiation: ab a^b Order of precedence 1. ^ 2. * and / 3. + and Use parenthesis to alter this order Example >>8+3*5 ans = 23 >>(8+3)*5 ans= 55
10

Assignment sign: = Use to assign a value to a variable Works differently than equal sign in math >>x = 3 equal sign >>x=x+2 add 2 to the current value of x, replace the current value with this new value. Whats on the left is assigned to whats on the right Cannot type in >>6 = x or >>x+2=20 Need not to declare the variables type

Working with numbers(II)

11

Working with numbers(I)

; suppresses screen printing

Complex numbers

12

Exercises I
1. A circular cylinder of height h and radius r is given by V=rh. A cylinder has h=15m with r=8m. What is the radius of another cylinder with same height but with a volume 20% greater? Given x=-5+9i and y=6-2i, show that x+y=1+7i, xy=-12+64i and x/y=-1.2+1.1i. Compute the magnitude M of (x+y) and the angle . Type in the sequence of operations solving the following quadratic equation: The equation describing the loading a capacitor C through a resistor R is given by: how long will it take for the voltage VC across the capacitor to reach 63% of its final value considering VC_final = 10V, R=10k and C=10F? Compare to the product RC.
13

2. 3. 4.

Overview
What is Matlab? Getting started Working with numbers Working with vectors and Matrices Using figures Scripts and M-files Signal analysis with Matlab
Arrays Figures

14

Array/Vector example (I)


Define a vector name=[start_val:end_val] or name=[start_val:increment:end_val]

Names are case sensitive v2 V2

Multiplication element wise: .

Not

15

Vector usefull commands


Command
X=[1 2 4 5 7 3] returns vector (1,2,4,5,7,3) X=zeros(1,N) returns vector (0,0,0.,0) X=ones(1,N) returns vector (1,1,1.,1) X=(a:b:c) returns vector (a,a+b,a+2b,,a+kb) with k such as a+kb c <a+(k+1)b X(p:q) returns elements of X with index between p and q X=[x1 x2] concatenates x1 and x2 X=x1+x2 adds x1 to x2 elements wise X=x1.*x2 multiplies x1 by x2 elements wise X is the transposed of X
16

Array/vector as polynomials
Ex: x3 2x + 5 is entered as >>p=[1 0 -2 5] decreasing power of x

Vector contains coefficients of a polynomial Polynomials are added using + Polymials are multiplied by conv (convolution) not Use function root to ge the roots of a polynomials
Example
>>roots(p) ans= -2.0946 1.0473+1.1359i 1.0473-1.1359i
17

Working with matrices

Matrices are entered just as vectors except that each row is separated by a ; or a return Command

matrix_name(:,N) returns column N of matrix_name Size(matrix_name) returns the size of the matrix (rows and columns) Det(matrix_name) computes the determinant of matrix_name Inv(matrix_name) gives the inverse of matrix_name

18

Defining signals (I)


Vectors can be used to define functions, such as y=f(x), where x is an N-element vector. Example: Useful to define signals: sin/square/ waves, Beware: sampled signals! In the example vector y does not take any value between 2 and 2 but 2, -1.99, -1.98 1.99, 2.
19

>>x=[-2:0.1:2]; >>y=x.^2+2;

Overview
What is Matlab? Getting started Working with numbers Working with vectors Using figures Scripts and M-files Signal analysis with Matlab

20

Using figures (I)


Matlab has several plot functions, the simplest plot allows to plot vectors versus another one/ The previous example can be plotted by typing plot(x,y) to plot y versus x

Sampled!

Interpolated!

Other types are:

plot3(x,y,z) 3D plot, useful to plot versus a parameter semilogx x-axis logarithmic scale (base 10) loglog y and x-axis logarithmic scale (base 10)
21

Defining signals (II)

A vector only contains values representing magnitude (y-axis), does not carry any information pertaining to the x-axis. Must associate a second vector defining versus what the first vector is plotted

same Y-axis vector

NOT the same X-axis vector

22

Using figures (II): sampling

10 samples/period

40 samples/period

Not enough points: aliasing!!!


23

Using figures (III)


Multiple plots: >>plot(x,y1,x,y2,xN,yN) Create a new figure: >>figure(handle) Add a title: >>title(your text) Add axis name: >>xlabel(your text) Add a legend: >>legend(y1,y2yN) Change axis limits: >>axis([xmin xmax ymin ymax]) text on the figure: >>text(xpos,ypos,your text )
Adding a grid: >> grid on

24

Using figures (IV)


Can have several subplot on the same figure. Use subplot(m,n,p) to break the figure window into an mby-n matrix, select the pth for the current plot Example:

25

Overview
What is Matlab? Getting started Working with numbers Working with vectors Using figures Scripts and M-files Signal analysis with Matlab

26

M-files: Script files


Its a bit tedious to use the interactive mode when you have many commands to run.

Use script files to put all commands in a file (text file) and run it (as you do in DOS (.bat) or UNIX, except no need to make it executable) To run the file, simply type its name (of course, you need to be in the directory where the script is saved to run it!) Use UNIX commands such as pwd, cd

27

Script example

2 curves on same plot Figure options

To run the script, in the command window type: >>plotexample

28

M-file: Functions

As in any programming language, you can: Pass on parameters Call other Matlab functions Actually, that is what is done is the previous script when the plot function is called! Script with parameter starts with something like function y = myfunc(param1, param2, ) myfunc returns y and accepts param1 and param2 as input parameters name the file after the functions name

29

Control Statement in Matlab


For Loops If
For i=1:n, <statements> end

If (condition) <statements 1> else <statements 2> end

Also exists while loops

30

Writing programmes
A good practice when you have to write a programme consists in

Not rushing to type-in lines of codes, usually means wasting time. Instead take time to analyse the problem Write up a pseudo code describing the tasks to perform (paper and pen!!!!) to solve the problem translate that in the chosen programming language, i.e. in Matlab. Do comment your programme.

IT SAVES TIME, EASIER TO DEBUG


31

1. 2. 3. 4.

Exercises 2

Using the command interpreter window, create the following vector in 2 different ways: A = 1 2 3 4 5 6 7 8 9 10 Using the command interpreter window ,create polynomial s4+1 and solve it. Write a function called CylinderVolume which returns the volume of a cylinder given its radius and its height (see exercise 1 of slide 13). Write a function called LPF which outputs the Bode plot of a Low Pass Filter (Bode plot: gain in dB and phase as a function of frequency). The transfer function a low pass filter is defined as:
2

Gain (in dB) defined as: G(f) = 10Log10 H(f) Where fc is the cut-off frequency entered as a parameter. To plot see semilogx ()
32

Exercise 3: write a script file to display the following 2 figures.

Figure 1

Figure 2
33

Exercise 3 (cont)
a) b)

The sine wave: frequency = 100kHz Amplitude = 0.3 V and a phase= 30. Use enough sampling points! Amplitude modulated signal given by:
Modulating signal: cosin wave with amplitude a=0.1 and frequency fm=5kHz Carrier: sinwave with amplitude A=1 and frequency fc=100kHz

All waveforms use the same time vector

c)

Random signal with normal amplitude distribution lying between 0.1 and 0.1 (see functions rand and randn) d) Define a random phase modulated sinwave using the white noise signal defined above. e) Create a new figure and plot the histogram of the random signals amplitude (function hist) To plot several plots in a same figure, use the function subplot

34

Exercise 4 (Control statements)


Write a function add to add two matrices entered as parameters and returns the result as a third matrix. Write a function mult to multiply two matrices entered as parameters and returns the result as a third matrix. Your 2 functions must check that the input matrices are compatible for addition and multiplication.

35

Overview
What is Matlab? Getting started Working with numbers Working with vectors Using figures Scripts and M-files Signal analysis with Matlab

36

Analysing and using signals to


Extract signal from noise Obtain frequency spectrum Obtain

Study data from measurements / simulations tools to

Generate data in a specific format to test a given system


Emulate data sent over a given noisy channel

37

Importing data

Can import data to Matlab.

Useful to work with actual or simulated signals.


x0 x1 x2 . . . xn-1 xn y0 y1 y2 . . . yn-1 yn

Data points saved in comma separated format:

Might need some reformating (either manual or automated)

Use the load command

>> load filename.ext creates an N dimension array where N = number of columns in the file

38

Exporting data
Can export data from Matlab.
>>save filename.txt variable_name

Useful to emulate signals to test actual systems. Data saved in text file

add ascii at the end of the line to in ascii Vectors are saved as a line, to save as a column must transpose first the vectors. To save several data in the same file, type
>>save filename.txt variable1 variable2

39

Fourier Transform

Study signal in frequency domain, i.e. find harmonics Harmonic: periodic signal = sum of elementary sinus and cosinus (a Fourier series) at frequencies equal to a multiple of the signals frequency f0.

Fourier transform: The Fourier transform of a single sinus (or cosinus) is a Diracs delta function at the sinus frequency
FT

time T

freq 1/T

40

Discrete Fourier Transform

Fourier transform works for continuous signals, for discrete signals use Discrete Fourier Transform

s(k) : kth time sample S(n) : nth frequency sample Ts : sampling period fd : DFT frequency step 1/(N.Ts) Accuray is 1/observation time Highest valid frequency: Nyquist frequency = 1/(2Ts) (corresponds to frequency index = N/2). Above -> aliasing Use a specific algorithm :Fast Fourier Transform

41

DFT: an example (I)


A signal is defined as followed (4 time samples given)

s(k)=1 s(k)=0
1

if k =0 ,1 otherwise

Compute the 4 frequency samples using:

42

DFT: an example (II)

43

FFT with Matlab

Matlab has a built-in function to compute the FFT: fft Y=fft(X) is the discrete Fourier transform of vector X (remember: a vector is a sampled signal!) Y=fft(X,n) is the n-point FFT. If the length of X is less than n, X is padded with trailing zeros to length n. Try to choose n=2p

where

fft yields complex numbers! To plot use magnitude


44

FFT: example
Magnitude of fft

2 peaks!!! And symetrical with respect to vectors length/2

Frequency not @ 50Hz -> plotted versus the index of the samples, not versus frequency

45

FFT: how to correctly plot


sample index vector after FFT 1 2 1.5 6 N/2+1 0.2 0.3 0.6 0.6 0.3 0.2

FFT is periodic, hence the symmetry Only one half to be taken into account
N 6 1.5 2

+
2 1.5 6 0.2 0.3 0.6

Fold

=
vector to plot 4 3 12 0.4 0.6 1.2

>>freq_vect=[0:N/2-1]*fsampling/N It is usually better to plot the FFT using semilog plot (frequency axis)

In practice, multiply 1st half by 2 and discard the 2nd half The frequency vector to define is linked the the sampling frequency, i.e. the time step between 2 consecutive data. Plot from 0Hz up to the Nysquist Frequency (fsampling/2) by step of fsampling/N

46

Frequency ok Magnitude not ok (x1024 too large) Divide by N to get Correct magnitude

ZOOM

47

6.

Exercises 5

For each waveform in figure 1, compute and display its frequency spectrum. You need to compute the FFT (Fast Fourier Transform), see matlab function fft. You need to create a suitable frequency vector.

48

Basic linear algebra with MATLAB


Norms and distances Solution of a linear system of equations Computation of Eigenvalues and Eigenvectors Singular Value Decomposition (SVD)

49

Norms and distances

50

Solution of a linear system of equations


By using the matrix inverse: >>x=inv(A)*b By using Gauss elimination (usually better): >>x=mldivide(A,b) (equivalently A\b) By using an iterative method >>help cgs >>help bicgstab >>help gmres >>help tfqmr
51

Computation of EigenEigen-values/values/-vectors

52

Exercise 6

53

Simulink
Graphical interface Used built-in block, no code to write. Easy to use Dedicated libraries: Laplace, Z-transform, communicationsand many more. Can write your own block either as M-file or in C programming language.

54

To kickkick-off Simulink
Simulink librairies

Click on Start
55

Example:

Block diagram of first model

56

Adding block from libraries

To open a block library, double click on the associated library icon in the Simulink block library window. After opening the Sources library, the Sources library window opens, as shown below. To add the first block to the diagram, point the mouse at the Sine Wave block in the Sources library window and press the left mouse button. Without releasing the left mouse button, drag the mouse to the new model window and release the mouse button.

57

I/Os and connections


The inputs to a block are on the left, a > symbol points into the block. In addition, outputs are generally on the right, a > symbol points out of the block. Start by connecting the output of the Sine Wave block to the topmost input port of the Mux block. To start, use the mouse to position the pointer over the output port of the Sine Wave block. Notice that the pointer changes to cross hairs, this is how Simulink indicates that it can start a connection. Without moving the mouse, press and hold down the left mouse button. Use the mouse to move the cross hairs to the topmost input port of the Mux block. In moving the mouse with the left button pressed, two things happen. First, a dashed line is drawn, this will be the connection line. Second, when the cross hairs arrive at the input port to the Mux bloc, the cross hairs change in appearance to double cross hairs, this is how Simulink indicates that its ready to complete the connection. With the mouse positioned, release the left mouse button.
58

Annotation and signals labels

To create a model annotation, double click in an unoccupied area. A small rectangle appears and the pointer changes to a vertical insertion bar. Start typing the annotation content. To start a new line, simply press the Enter key. To close the annotation, click with the mouse elsewhere in the window. To move an annotation, drag it to a new location. To change the font size of an annotation, select it and with the mouse select Format=>Font. In the pop-up window select the desired font size and then click OK. The font size will change when the annotation is deselected, to do so simply click elsewhere. To create a signal label, double click on a line segment and type the label at the insertion point. When you click on another part of the model, the label fixes its location. Take care to double-click on the line. If you double click in an unoccupied part of the model, you will create a model annotation instead.
59

Model parameters and simulation


Double click on the block to see its parameters. Modify them note that the frequency is specified in rad/sec. Amplitude are unitless Simulation parameters:

Run the simulation by clicking on Simulation and next Start .

Need to set the final time Eventually stet the max step to a correct value Eventually modify the solver.

60

Exercise 7
Create a model of an ideal amplifier. Use a sinusoide with amplitude A=1, f=100kHz. Plot both the input and the output of the amplifier. Create a model of an amplitude modulated signal. Use as carrier a sinwave with A=1, fc=1MHz, use as sinwave with A=0.3 and fm=100kHz. Generate I/Q signals and then create a model of an QAM-16 demodulator (4-bits). The data I and Q are read from files. The data rate is 1MHz. The constellation to decode is given next.

61

I comparators

b0 b1

cos(2f0t) x(t) sin(2f0t) Q comparators b3 b2

62

Vectors: exercises

10 samples/periode

40 samples/periode

63

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy