Purpose of the lecture MATLAB Harri Saarnisaari, Part of Simulations and Tools for Telecommunication Course This lecture contains a short introduction to the MATLAB For further details see other sources Later we will apply Matlab to a simple simulation exercise of a communication system In that exercise we study, at the same time as learning MATLAB, different aspects of communication simulations 2 MATLAB MATLAB is an interactive, matrix-based system for scientific and engineering numeric computation and visualization You can solve complex numerical problems in a fraction of the time required with a programming language such as Fortran or C. The name MATLAB is derived from MATrix LABoratory MATLAB MATLAB is an expression language the expressions you type are interpreted and evaluated MATLAB statements are usually of the form variable = expression, or simply expression 3 4 1
MATLAB MATLAB contains several build-in functions Written either using C, or as a form of m-files You can create your own functions (m-files) Most of work is writing functions that are used to execute simulations You can obtain functions (m-files) written by others BUT, AS ALWAYS, Remember to validate all the functions (if not already validated by others) Even build-in functions may contain errors, or are not usable in your problem since every numeric algorithm has its limitations remember to check the function manual MATLAB MATLAB has its core with some basic functions (which can be used to build everything) In addition, it has TOOLBOXes that include buildin functions to support different areas or multiple of areas TOOLBOXes ease and fasten simulations in their areas Naturally, one has to learn how to use functions in TOOLBOXes 5 6 MATLAB TOOLBOXes need licenses Usually university has a large number of licenses for basic toolboxes and less for rare ones Basic MATLAB is, naturally, common Signal processing, etc toolboxes are common for many units and thus often available Communications needed in communications and, thus, more rare MATLAB Occasionally, licenses run out, and you cannot simulate A solution: use basic functions in your simulator if possible (although TOOLBOXes are made to speed up/ease your work) Especially useful if you need only once or twice a function from a rare TOOLBOX (and that function is simple to replace) E.g., use common randn to create AWGN noise instead of awgn from COMMONUCATION TOOLBOX 7 8 2
Toolboxes Toolboxes 9 10 Information sources, help Matrices MATLAB primer http://ise.stanford.edu/matlab/matlab-primer.pdf Guide to basic properties, very helpful if read and executed simultaneously Mathworks home page http://www.mathworks.com/ Information of all MATLAB related products Tutorials Helps of functions (m-files) Build-in and user created m-files from several areas To see the code, do type m-filename MATLAB can efficiently use matrices and vectors MATLAB handles vector vector and matrix vector products faster than for loops (if sizes are not too large) Many books and papers where you can find algorithms use matrix notation So, learn to use matrices and vectors efficiently! Learn also matrix & vector functions: these may fasten your efforts The same holds also for other things: You should know what to do and know math behind the things to use MATLAB efficiently MATLAB can also be used inefficiently by just doing things by a brute-force coding 11 12 3
Matrices A hint: always write vectors in the same way (otherwise you will have problems) Either as a column or row vector x=x(:) makes a column vector from x Column form is the most common Matrices The same way definition is also important since algorithms often required transpose or complex conjugate transpose (typical in communications) Let A be a matrix and x, y be vectors In Matlab the complex conjugate transpose is x Often meet operations are A*x x *y (which is different than (transpose of x) * y if x is complex), x *A*y Problem point: if you do not use the same way definition x column, y row: then x *y is not defined!! 13 14 Other helpful matrix hints: Matrices Matrix of ones: ones(n,m) Matrix of zeros: zeros(n,m) Element wise matrix product z(i)=x(i)*y(i) z=x.*y (with dot) C=A.*B Copy (instead of for loop) Kronecker product: kron(a,b) copies A multiplied by elements of B, e.g. kron(x,ones(2,1)) makes two copies of x M-files You can call m-files in the command line or inside m-files You can use other m-files in your simulations A good practice is to make small, general-usable m-files (if possible) and then apply them in your master simulation m-file The generality allows you to apply the same m-file in many places Build-in m-files are general M-files are called such since they have file type.m 15 16 4
M-files M-files can be either script files or function files A script file consists of a sequence of normal MATLAB statements When the m-file is called, the statements are executed Variables in a script file are global and will change the value of variables of the same name in the environment of the current MATLAB session 17 Script file example We want to calculate logarithm (base 10) of 10 In command line it is log10(10) (since log is ln) Put this as a variable a=log10(10) Create m-file which calculates base 10 logarithm of 100, and puts the result in a variable a, name this as testa.m ---m-file---- a=log10(100) ------------- Execute first a=log10(10) and then testa.m 18 If the result is not a named variable Matlab gives ans Value of variable a changes since script files have global variables M-files Function files provide extensibility to MATLAB You can create new functions specific to your problem which will then have the same status as other MATLAB functions Variables in a function file are by default local Locality means that a value of variable on the command line is not changed even if a function file contains the same variable A variable can, however, be declared global 19 20 5
M-files M-files Inputs to function files may be variables Format function [out variables]=m-filename(in variables) statements Out variables are those variables you need at the output E.g., channel output In variables are those you need to execute the m-file E.g., channel input Some in variables may be optional; a default value is given if not at the input 21 Inputs to function files may be variables Format function [out variables]=m-filename(in variables) statements Remember to comment your files you may even create a help part that explains what the function does Commenting helps you and others to remember what the different lines do and what for the different variables are Try to use representative variable names 22 Function file example We create a function file that computes a sinusoidal function with a frequency f over an interval 0 - T results values of a sinusoidal and the interval And plots the signal In addition We make a help and comment the file function [y,t]=testb(f,t,n); %[y,t]=testb(f,t,n) plots a sinusoidal with a frequency f [Hz] %over an interval 0 - T [s] and results values of the function y and %corresponding time instants. n is the number of time instants, %the default being 128. % %by Michael Mfilewriter, 2006 %check if n is given or not %if not set it as default if nargin<3, n=127; else n=n-1; %makes sure that we have n time instants end 23 24 6
%create time scale with n steps t=0:t/n:t; t=t(:); % t(:) makes a column vector [y,t]=testb(1,10,1024) results %compute values of sinusoideal y=sin(2*pi*f*t); %plot it with t as a x-axis and y as a y-axis plot(t,y) xlabel('time [s]') %creates text for x-label ylabel('sinusoidal') %creates text for y-label 25 26 Help If m-files have a help it is called as help m-file E.g., if we call help of testb.m as help testb It results [y,t]=testb(f,t,n) plots a sinusoidal with a frequency f [Hz] over an interval 0 - T [s] and results values of the function y and corresponding time instants. n is the number of time instants, the default being 128. by Michael Mfilewriter, 2006 That is, help results everything commented (by %) in the code before first line without % More on Variables Global Simulation sub-files (m-files) may require a huge list of inputs, and many of them the same inputs To save input writing efforts it may be desirable to use a global variable But, be aware, do not use the same name for anything else, otherwise its contents is changed since it is global Therefore, the name of the global variable is often complicated (representative, hopefully), not just x 27 28 7
More on Variables More on Variables How to Define global X, Y, Z (where X, Y, Z are variables) at every m-file you want them to be global E.g. In workspace global X In your m-file1 (there is a line) global X In your m-file2 global X 29 Structures Structures are an efficient way to manage variables in complicated simulations and form global variables A structure could contain matrices, vectors, variables, strings (=text) E.g. create a global variable G and store all (needed) variables under it, e.g., G.TX.filter, G.TX.modulation, G.RX.filter, G.RX.equalizer, G.channel.awgn 30 More on Variables Alternatives Structure examples Define structure variables S.a.a=1;S.a.b=2;S.b.a=3;S.b.b= awgn ; Results: S = a: [1x1 struct] b: [1x1 struct] S.a (this lists all S.a variables, now S.a.a and S.a.b) ans = a: 1 b: 2 S.a.a (this form gives you the variable value you need in calculations) ans = 1 S.a.a*S.b.a ans = 3 S.b.b ans = awgn 31 Often, simulations include checking of alternative use cases/solutions SWITCH CASE END is a tool for this E.g. channel= AWGN ; %alternatives AWGN, RAYLEIGH switch channel case{ AWGN } Statements case{ RAYLEIGH } Statements end 32 8
Visualization of the results is an important part of researchers work MATLAB offers a lot of alternatives 2D figures Plot, semilogy, 3D figures Mesh, surf, Not only are the graphs important, but also that you mark what is in the figure (otherwise, nobody knows what is in there) Labels, legends 33 Example We plot four curves, give them different look to be separated in color (screen) and appearance (black & white used in journals and prints) Name the curves We create labels with units 34 : result t=0:3:27; %X-axis A=ones(10,1);B=3*A;C=2*t-4;D=-1.5*t+4; plot(t,a,'-b',t,b,'-g*',t,c,'rd-.',t,d,'--mo') xlabel('t [s]'),ylabel('power [db]') legend('a','b','c','d') 35 36 9
Not all colors are well seen in B&W, be careful You can add title( ) (at top of fig) You can add text by cursor click using gtext( ) You can modify things by figure tools You can zoom, increase line width, move the legend box, etc You can set axis scale by axis([xmin xmax ymin ymax]) etc Various line types, plot symbols and colors may be obtained with PLOT(X,Y,S) where S is a character string made from one element from any or all the following 3 columns: b blue. point - solid g green o circle : dotted r red x x-mark -. dashdot c cyan + plus -- dashed m magenta * star (none) no line y yellow s square k black d diamond w white v triangle (down) ^ triangle (up) < triangle (left) > triangle (right) p pentagram h hexagram Italic color: seen in B&W 37 38 You can create several plots into the same figure element E.q. subplot(2,1,1) divides figure element into 2x1 array and activates element 1, subplot(2,1,2) activates the second one More on knowhow: filtering Filtering of a signal is needed in many cases Based on theory it could be implemented As a convolution As a filter Using frequency domain means (since convolution correspond the multiplication in the frequency domain) Overlap-add or overlap-save structures 39 40 10
More on knowhow: filtering MATLAB has all these, we look only filter y=filter(b,a,x) ARMA filter model Y(z)=[B(z)/A(z)] X(z) y output y feedforward filter taps a feedback filter taps x input 41 More on knowhow: filtering We create a 4 times oversampled signal with square pulse shape x=2*round(rand(12,1))-1; %random data 12 points X=kron(x,[1;0;0;0]); %interpolation (see the previous lecture) 48 points a=1;b=[1 1 1 1]; %filters y=filter(b,a,x); %filtering plot(y) axis([0 50-1.1 1.1 ]) 42 x= 1 1 1-1 1-1 1-1 -1-1 -1 1 43 11