it has several advantages over high-level programming

20
Introduction to MATLAB Dr. Harris Tsimenidis Newcastle University School of Engineering September 2018 1/80 MATLAB Advantages It has several advantages over high-level programming languages, such as C/C++, Fortran etc. A large set of toolboxes is available. A toolbox is a collection of MATLAB functions speciïŹc for a subject, e.g. the signal processing toolbox or the control toolbox. Over 8000 functions available for various disciplines. At any time, variables (results of simulations) are stored in the workspace for debugging and inspection, Excellent visualization (plots) capabilities, Easy programming, e.g. it is not required to deïŹne variable types (unless needed). All variables are usually of type double (64 bit or 8 byte representation). Quick code development. 2/80 MATLAB Disadvantages Very expensive for non students, although there are some free clones, such as Octave or Scilab that are MATLAB compatible (but not 100%). Code execution can be slow if programmed carelessly without vectorization. Algorithms developed in MATLAB will need to be translated in C, VHDL or assembly to be used in DSP or FPGA platforms. 3/80 The MATLAB IDE 4/80

Upload: others

Post on 14-Nov-2021

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: It has several advantages over high-level programming

Introduction to MATLAB

Dr. Harris Tsimenidis

Newcastle UniversitySchool of Engineering

September 2018

1 / 80

MATLAB Advantages

It has several advantages over high-level programminglanguages, such as C/C++, Fortran etc.

I A large set of toolboxes is available. A toolbox is acollection of MATLAB functions specific for a subject, e.g.the signal processing toolbox or the control toolbox.

I Over 8000 functions available for various disciplines.I At any time, variables (results of simulations) are stored in

the workspace for debugging and inspection,I Excellent visualization (plots) capabilities,I Easy programming, e.g. it is not required to define variable

types (unless needed). All variables are usually of typedouble (64 bit or 8 byte representation).

I Quick code development.

2 / 80

MATLAB Disadvantages

I Very expensive for non students, although there are somefree clones, such as Octave or Scilab that are MATLABcompatible (but not 100%).

I Code execution can be slow if programmed carelesslywithout vectorization.

I Algorithms developed in MATLAB will need to be translatedin C, VHDL or assembly to be used in DSP or FPGAplatforms.

3 / 80

The MATLAB IDE

4 / 80

Page 2: It has several advantages over high-level programming

The MATLAB IDE: Command WindowI The command window can be used to enter variables and

perform simple computations:

1 x=12 y=23 z=x+y4 phi=cos(x)

I Basic arithmetic operators can be used such as+, -, *, /, ˆ

I Highest priority is from right to leftI Brackets can be used to make priorities clear:

1 4*2+3ˆ22 4*(2+3)ˆ2

I double is the default precisionI format long can be used to display more decimal points

5 / 80

The MATLAB EditorI Scripts are files with .m extensions.

I Newly created scripts names should not start with numbersor contain spaces.

I You should not use names for scripts and functions thatare already in use. The which command can be used tocheck if a name is already allocated, e.g. which clear

I They can be executed from the command prompt or bypressing F5 or from the corresponding entry in the Debugmenu or from the Play icon on the toolbar.

6 / 80

Help

To be typed in MATLAB command prompt followed by[Enter]:

I To check how the help command works: >> help helpI To check toolboxes available: >> helpI To check the elementary math function toolbox: >> helpelfun

I To check how the function fix works: >> help fixI To check functions available in the signal processing

toolbox: >> help signalI To check how the function fft works: >> help fftI More detailed help can be obtained using the doc

command.I The doc command displays help in a separate window.

7 / 80

The MATLAB IDE: Command HistoryI Command history window keep record of past command

prompt entries:

I To recall past commands highlight and press F9I Or directly drag and drop.I SHIFT and CTRL keys can be used in conjunction to select

a block or more than one individual entries.I Arrrow keys can be used to navigate through command

history entries.8 / 80

Page 3: It has several advantages over high-level programming

The MATLAB IDE: Workspace

I The workspace displays the variables stored in thememory during the current session.

I Workspace associated MATLAB commands:

1 clear % or clear all2 who3 whos

9 / 80

Working with Scalar Variables

I All scalar variables in Matlab are stored in doubleprecision (64 bits) unless explicitly specified.

I Defining scalar variables:

1 >> x=1, y=22 x =3 14 y =5 2

I Semicolon ; can be used to suppress displaying of resultsin command prompt:

1 >> w=3;

10 / 80

Special Variable Names and Constants

I ans: Most recent answer.I pi: π = 3.141592653589793

I eps: Smallest floating point number.I i, j, 1j: Imaginary unit/operator.I Inf or inf: Infinity (∞)I NaN or nan: not a number.I Tip: when programming overwriting/using this variables

and constants should be avoided.

11 / 80

Built-in Functions

I There is a vast amount of built-in functions in Matlabranging from elementary mathematical functions to higherlevel.

I In contrast to other programming languages such as Cmost of the functions accept complex arguments and canbe effortlessly applied to vectors and matrices.

I To inspect what is available:

1 >> doc elfun2 >> doc specfun

and then click on specific functions (cos, sin, etc.).I Alternatively, you can use the help command:

1 >> help elfun

12 / 80

Page 4: It has several advantages over high-level programming

Key Built-in Mathematical Functions

1 sqrt() % square root2 abs() % absolute value of of complex number3 angle() % angle of complex number4 exp() % Exponential5 real() % real part of complex number6 imag() % imaginary part of complex number7 cos() % Cosine of argument in radians8 sin() % Sine of argument in radians9 tan() % Tangent of argument in radians

10 acos() % Inverse cosine, result in radians11 asin() % Inverse sine, result in radians12 atan() % Inverse tangent, result in radians13 cosh() % Hyperbolic cosine14 sinh() % Hyperbolic sine15 tanh() % Hyperbolic tangent16 log() % Natural logarithm17 log2() % Base 2 logarithm18 log10() % Base 10 logarithm

13 / 80

Example: Mathematical ExpressionsInput impedance of a 75 Ω cable with a 50 Ω load at the end:

Zi(l) = Z0ZL + jZ0 tan(ÎČl)

Z0 + jZL tan(ÎČl)

Z0 = 50 Ω, ZL = 75 Ω, ÎČ =2π

λ, λ = 10 cm

I Matlab Implementation:

1 Z0=75;2 ZL=50;3 lambda=0.1;4 b=2*pi/lambda;5 l=0.05;6 Zi=Z0*(ZL+1j*Z0*tan(b*l))/(Z0+1j*ZL*tan(b*l))7 Zi =8 50.0000 - 0.0000i

14 / 80

Vector Arrays

Dr. Harris Tsimenidis

Newcastle UniversitySchool of Engineering

September 2018

15 / 80

Vector ArraysI Vectors are treated as 1D arrays (M × 1) or (1×N ):

x =

a1a2. . .aM

orx = [x1, x2, . . . , xN ]

I A scalar variable is a 1× 1 arrayI Vector indexing starts in Matlab with 1.I Vectors arrays can be entered in Matlab directly as:

1 >> x=[1, 2, 3, 4]2 x =3 1 2 3 4

I Commas are optional.16 / 80

Page 5: It has several advantages over high-level programming

The Colon Operator :

I Create vectors, array subscripting, and for-loop iterators.I Syntax: StartPoint:Step:StopPointI Unit spacing:

1 >> x=1:82 x =3 1 2 3 4 5 6 7 8

I Non-unit spacing:

1 >> y=-0.2:0.1:0.22 y =3 -0.2000 -0.1000 0 0.1000 0.2000

17 / 80

The Colon Operator : (Cont.)

I Negative non-unit spacing:

1 >> z=0.4:-0.1:02 z =3 0.4000 0.3000 0.2000 0.1000 04

5 >> w=0:pi/4:pi6 w =7 0 0.7854 1.5708 2.3562 3.1416

I Alternative: linspace

1 >> linspace(0.4,0,5)2 z =3 0.4000 0.3000 0.2000 0.1000 0

18 / 80

Element-by-Element Vector Array Operations

I Element-by-element multiplication .*

1 >> t=0:0.01:10;2 x=cos(2*pi*t).*exp(-0.1*t);3 plot(t,x)

I Element-by-element power .ˆ

1 >> x=-1:0.01:1;2 y=x.ˆ2.*(x.ˆ2+1).ˆ(1/2)3 plot(x,y)

I Element-by-element division ./

1 >> x=-2:0.01:2;2 y=x./sqrt(x.ˆ2+1)3 plot(x,y)

19 / 80

min, max Functions

I [C,I]=min() finds the indices of the minimum values ofA, and returns them in output vector I. If there are severalidentical minimum values, the index of the first one found isreturned.

I [C,I]=max() finds the indices of the maximum values ofA, and returns them in output vector I. If there are severalidentical maximum values, the index of the first one foundis returned.

1 x=randn(1,100);2 [minX,posMinX]=min(x);3 [maxX,posMaxX]=max(x);4 [minX,posMinX]5 -3.0292 886 [maxX,posMaxX]7 2.5260 14

20 / 80

Page 6: It has several advantages over high-level programming

find and sort FunctionsI ind=find(X) finds the indices and values of nonzero

elements in X.

1 >> x=randn(1,5);2 pos=find(x>0)3 pos =4 2 3 5

I [B,IX]=sort(A,...) sorts the array elements of A. inascending or descending order.

I The second argument is either ’ascend’ or ’descend’.

1 >> x=[7 4 1 10 0 9];2 [val,pos]=sort(x)3 val =4 0 1 4 7 9 105 pos =6 5 3 2 1 6 4

21 / 80

mean, var and std FunctionsI mean(x) computes the average value of a time seriesx(n) and is defined as

”x =1

N

N∑

n=1

x(n)

I var(x) computes the variance value of a time seriesx(n) and is defined as

σ2x =1

N

N∑

n=1

(x(n)− ”x)2

I std(x) is the standard deviation value of a time seriesand defined as σx (square root of the variance).

1 x=randn(1,1e5);2 [mean(x), var(x), std(x)]3 ans =4 -0.0006 0.9937 0.9969

22 / 80

Plotting

Dr. Harris Tsimenidis

Newcastle UniversitySchool of Engineering

September 2018

23 / 80

One-Dimensional Plots: The plot commandI Check how the plot command works via help plot or doc

plotI Initial example:

1 t=0:0.1:4;2 x=cos(2*pi*t).*exp(-0.6*t);3 plot(t,x)

0 0.5 1 1.5 2 2.5 3 3.5 4−1

−0.5

0

0.5

1

24 / 80

Page 7: It has several advantages over high-level programming

Line color, marker and line typeI The default behaviour be controlled via an additional

argument to (). The 3rd argument is a string that can becomposed as a combination of a line colour, marker andline type.

1 t=0:0.1:4; x=cos(2*pi*t).*exp(-0.6*t);2 y=sin(2*pi*t).*exp(-0.6*t);3 hold on, plot(t,y,’mo--’)

0 0.5 1 1.5 2 2.5 3 3.5 4−1

−0.5

0

0.5

1

25 / 80

The plot command: Line Colors and Types

Letter Line Colorb blueg greenr redc cyanm magentay yellowk blackw white

Symbol Line Type- solid: dotted-. dashdot– dashed(none) no line

26 / 80

The plot command: Markers

I The following markers are available:

Symbol Marker Type. pointo circlex x-mark+ plus* stars squared diamondv triangle (down)ˆ triangle (up)< triangle (left)> triangle (right)p pentagramh hexagram

27 / 80

hold and grid

I The hold command holds the current plot so thatsubsequent plots are superimposed.

1 hold on % sets the state of hold to on2 hold off % sets the state of hold to off3 hold % toggles the last state of hold

I To set the grid use the grid command. Available options:

1 grid on % turn grid on2 grid off % turn grid off3 grid % toggle last state of grid

28 / 80

Page 8: It has several advantages over high-level programming

The plot command: Two curvesI Plot two curves at the same time:1 t=0:99;2 noise1=randn(1,100);3 noise2=5+0.2*randn(1,100);4 plot(t,noise1,’ro-’,t,noise2,’bx--’)

0 20 40 60 80 100−10

−5

0

5

10

time (s)

Am

plit

ude

(V

)

Gaussian distributed random noise signal.

”=0, σ=1

”=5, σ=0.2

29 / 80

xlabel, ylabel, title, legendI Add axes labels and title

1 xlabel(’time (s)’)2 ylabel(’Amplitude (V)’)3 title(’Gaussian distributed random noise signal.’)

I Add a legend:

1 legend(’mu=0, sigma=1’, ’mu=5, sigma=0.2’)2 legend(’\mu=0, \sigma=1’, ’\mu=5, \sigma=0.2’)

I The legend command requires as many string argumentsas the curves used in the plot command.

I The position of the legend can be controlled by anadditional argument, i.e. ’Location’ followed by a stringspecifying the actual location.

I Examples for location: ’North’, ’South’, ’East’, ’West’,’NorthEast’, ’NorthOutside’ ’NorthEastOutside’, ’Best’,’BestOutside’, etc.

30 / 80

Axes Control

I Control the axes ranges viaaxis([XMIN, XMAX,YMIN, YMAX]):

1 axis([0 100 -4 6])

I Available axis() options:

1 % leave space so that legend does not cover graph2 axis([0 200 -5 10])3 % reshape plot axes to square4 axis(’square’)5 % turn axes off6 axis(’off’)7 % turn axes on8 axis(’on’)9 % return to normal

10 axis([0 100 -4 6])

31 / 80

Multiple Figures and Subplots

I Multiple plots can be created using the figure()command.

1 figure(1); plot(randn(1,100))2 figure(2); plot(rand(1,100),’r’)

I Subplots in the same figure can be created viasubplot(mnk), where m, n and k are integers.

I The pair m, n gives the size of the array of plots to begenerated, while k is used to index the plots.

I k=1 corresponds to the upper-left plot. k=m*ncorresponds to the lower-right plot.

I Plots are indexed row-wise for increasing k. If the indexk>n, a new row of plots starts.

32 / 80

Page 9: It has several advantages over high-level programming

Subplot Example1 subplot(221), t=0:0.01:8; plot(t,sinc(t))2 subplot(222), plot(t,cos(2*pi*t),’r’)3 subplot(223), plot(t,besselj(0,t),’m’)4 subplot(224), plot(t,log10(t),’k’)

0 2 4 6 8−0.5

0

0.5

1

0 2 4 6 8−1

0

1

0 2 4 6 8−0.5

0

0.5

1

0 2 4 6 8−2

−1

0

1

33 / 80

Other Plot Types

I semilogx(): Logarithmic x-axis.I semilogy(): Logarithmic y-axis.I loglog(): Logarithmic x and y-axis.I stem(): Discrete-time plot.I plotyy(): Plot with 2 y-axis.I bar(): Bar graph.I pie(): Pie graph.I plot3(): 3-D plot.mesh 3-D mesh surface.I mesh(): 3-D mesh surface.I surface(): Create surface.

34 / 80

Working with Array Variables

Dr. Harris Tsimenidis

Newcastle UniversitySchool of Engineering

September 2018

35 / 80

Arrays: Vectors and MatricesI Vectors are treated as 1D arrays (M × 1) or (1×N ):

x =

a1a2. . .aM

orx = [x1, x2, . . . , xN ]

I Matrices are treated as 2D arrays (M ×N )

A =

a11 a12 . . . a1Na21 a22 . . . a2N. . . . . . . . .aM1 aM2 . . . aMN

I A scalar variable is a 1× 1 arrayI Matrix and vector indexing starts in Matlab with 1.

36 / 80

Page 10: It has several advantages over high-level programming

Entering Arrays

I Matrices can be entered in Matlab via different ways, e.g.by entering an explicit list of elements:

1 >> x=[1 2 3 4]2 x =3 1 2 3 44 >> y=[5, 6, 7, 8]5 y =6 1 2 3 47 >> A=[1 2 3 4; 5 6 7 8]8 A =9 1 2 3 4

10 5 6 7 8

I Elements on the same row are separated by space orcomma.

I New line is started with semicolon.

37 / 80

Array Indexing

I To address a array elements:

1 >> x=1:4; A=[x;x+4];2 >> x(2)3 ans =4 25 >> A(2,2)6 ans =7 6

I end can be used for the last elements:

1 >> x(end)2 ans =3 44 >> A(end,end)5 ans =6 8

38 / 80

Array Indexing using :

I To address the full column of a matrix:

1 >> A(:,2)2 ans =3 24 6

I To address the full row of a matrix:

1 >> A(2,:)2 ans =3 5 6 7 8

39 / 80

Value Assignment on Array Elements

I To assign a value to a specific array element:

1 >> x(end)=102 x =3 1 2 3 104

5 >> A(1,2)=36 A =7 1 3 3 48 5 6 7 8

I Multiple elements can be assigned at once:

1 >> A(:,3)=[1 1]2 A =3 1 3 1 44 5 6 1 8

40 / 80

Page 11: It has several advantages over high-level programming

Array Concatenation

I Arrays can be concatenated by using the [] operator.I However, this can be inefficient and time consuming for

large arrays.

1 >> x=1:5; y=x+5; z=y+5;2 >> A=[x;y;z]3 A =4 1 2 3 4 55 6 7 8 9 106 11 12 13 14 15

1 >> B=[A A; A A]2 B =3 1 2 3 4 5 1 2 3 4 54 6 7 8 9 10 6 7 8 9 105 11 12 13 14 15 11 12 13 14 156 1 2 3 4 5 1 2 3 4 57 6 7 8 9 10 6 7 8 9 108 11 12 13 14 15 11 12 13 14 15

41 / 80

Deleting Array Rows or Columns

I Deleting rows:

1 >> A(1,:)=[]2 A =3 6 7 8 9 104 11 12 13 14 15

I Deleting columns:

1 >> A(:,1)=[]2 A =3 7 8 9 104 12 13 14 15

42 / 80

Matrix and Vector SizesI The length of a vector can be checked via the length

command:

1 >> x=1:82 x =3 1 2 3 4 5 6 7 84 >> length(x)5 ans =6 8

I The size of a matrix can be checked via the sizecommand:

1 >> A=[1:5;6:10]2 A =3 1 2 3 4 54 6 7 8 9 105 >> size(A)6 ans =7 2 5

43 / 80

Elementary Array Generating Functions

Matlab provides several functions that generate basic matrices:I zeros(M,N) and ones(M,N)I rand(M,N) generates random numbers uniformly

distributed between [0, 1]:I randn(M,N) generates random numbers that are

Gaussian distributed with mean 0 and standard deviation 1I randi([IMIN,IMAX],M,N) generates random integer

numbers from a uniform discrete distributionI eye() generates the identity matrix:

44 / 80

Page 12: It has several advantages over high-level programming

Vector and Matrix Operations

I Operatorsp Transpose if matrix is real: AT

or Hermitian transpose if matrix is complex: (A∗)T ,.p Transpose if matrix is real or complex: AT .+ Addition- Subtraction* Multiplication/ Divisionˆ Power

45 / 80

Transpose OperatorI Transpose of vectors:

1 >> x=1:22 x =3 1 24 >> x’ % or x.’ or transpose(x)5 ans =6 17 28 >> v=[1-j 2+j]9 v =

10 1.0000 - 1.0000i 2.0000 + 1.0000i11 >> v.’12 ans =13 1.0000 - 1.0000i14 2.0000 + 1.0000i15 >> v’ % Note how the imaginary parts change sign16 ans =17 1.0000 + 1.0000i18 2.0000 - 1.0000i

46 / 80

Transpose Operator (Cont.)

I Transpose of a matrix:

1 >> A=[1:3; 4:6]2 A =3 1 2 34 4 5 65 >> size(A)6 ans =7 2 38 >> B=A.’9 B =

10 1 411 2 512 3 613 >> size(B)14 ans =15 3 2

47 / 80

Array Addition/Subtraction

I Vectors:

1 >> x=1:42 x =3 1 2 3 44 >> y=5:85 y =6 5 6 7 87 >> z1=x+y8 z1 =9 6 8 10 12

10 >> z2=x-y11 z2 =12 -4 -4 -4 -4

I Matrices:

1 >> A=[x;y]2 A =3 1 2 3 44 5 6 7 85 >> B=ones(2,4)6 B =7 1 1 1 18 1 1 1 19 >> C=A+B

10 C =11 2 3 4 512 6 7 8 913 >> D=A-B14 D =15 0 1 2 316 4 5 6 7

48 / 80

Page 13: It has several advantages over high-level programming

Array MultiplicationI Multiplication of vectors and matrices:

1 >> x*y2 ??? Error using ==> mtimes3 Inner matrix dimensions must agree.

Inner dimensions of vectors must be correct formultiplication, e.g. (1×N)(N × 1) or (N × 1)(1×N):

1 >> transpose(x)*y % or x’*y2 ans =3 5 6 7 84 10 12 14 165 15 18 21 246 20 24 28 327 >> x*transpose(y) % or x*y’8 ans =9 70

The later is equal to the dot product of two vectors.

49 / 80

Array Multiplication (Cont.)

I Inner dimensions of matrices must be the same formultiplication, e.g. (M ×N)(N ×M) or (N ×M)(M ×N):

1 >> A*B2 ??? Error using ==> mtimes3 Inner matrix dimensions must agree.4 >> A*transpose(B) % or A*B’5 ans =6 10 107 26 268 >> transpose(A)*B % or A’*B9 ans =

10 6 6 6 611 8 8 8 812 10 10 10 1013 12 12 12 12

50 / 80

Matrix Division

I Matrix division for square matrices:

1 >> A=magic(3)2 A =3 8 1 64 3 5 75 4 9 26 >> A/A7 ans =8 1 0 09 0 1 0

10 0 0 111 >> A*inv(A)12 ans =13 1.0000 0 -0.000014 -0.0000 1.0000 015 0.0000 0 1.0000

51 / 80

Matrix Power and Inverse

I Power of a matrix:

1 >> Aˆ2 % same as A*A2 ans =3 91 67 674 67 91 675 67 67 91

I Matrix needs to be square for the inverse to exist:

1 >> A=[1 1; -1 1]2 A =3 1 14 -1 15 >> V=inv(A)6 V =7 0.5000 -0.50008 0.5000 0.5000

52 / 80

Page 14: It has several advantages over high-level programming

Matrix Inverse (Cont.)

I For non-square matrices use pseudo-inverse:

1 >> A=[1 1; -1 1; 0 1]2 A =3 1 14 -1 15 0 16 >> V=pinv(A)7 V =8 0.5000 -0.5000 09 0.3333 0.3333 0.3333

53 / 80

Scripts and Functions

Dr. Harris Tsimenidis

Newcastle UniversitySchool of Engineering

September 2018

54 / 80

Scripts and Functions

I Scripts and functions are files with .m extensions.I Newly created scripts and functions names should not

start with numbers or contain spaces.I You should not use names for scripts and functions that

are already in use. The which command can be used tocheck if a name is already allocated, e.g. which fft.

I Scripts execute the MATLAB commands found in the file.I Scripts have no input or output variables.I To create a script from the command prompt: >> editfilename.m

I Alternatively, you can use the corresponding toolbar iconor the new file menu entry.

I Variables created by a script are available in theworkspace.

55 / 80

Scripts and Functions (Cont.)

I Example: (type in a file test.m and run)

1 clear, clc, close all2 x=randn(1,10);3 plot(x)4 whos5 Name Size Bytes Class Attributes6 x 1x10 80 double

I Functions may have input and output variables.I m-file function syntax: function [out1, out2, ...]= funname(in1, in2, ...)

I Comments about the function usage can be put after thefunction declaration for clarity.

I The MATLAB functionality can be extended by creatingnew functions to solve a specific problem.

56 / 80

Page 15: It has several advantages over high-level programming

Function ExampleI The following code creates a new MATLAB function that

generates Gaussian noise with specified mean andstandard deviation. Type it in a file gauss.m:

1 function x = gauss(M,N,m,s)2 %GAUSS - Generates Gaussian noise samples3 % Usage: x = gauss(M, N)4 % M, N: Dimensions of the output noise matrix x5 % m, s: Mean value and standard deviation of x6 x=m+s*randn(M,N);

I Type >> help gauss to see the output message.I To run the function gauss:1 >> y=gauss(1,1e5,0,1);2 >> [mean(y), std(y)]3 ans =4 -0.0003 0.9997

I Note how the variable x of the function is not available inthe workspace after the function call.

57 / 80

Scripts and Functions (Cont.)

I If no output argument is used the first output variable isstored in ans.

1 >> gauss(1,5,1,0.5)2 ans =3 1.4357 0.9435 0.8946 1.1852 0.8910

I Functions may have multiple outputs.

1 function [x, me, se] = gauss(M,N,m,s)2 %GAUSS - Generates Gaussian noise samples3 % Usage: x = gauss(M, N)4 % M,N: Dimensions of the output noise matrix x5 % m,s: Mean value and standard deviation of x6 % me,se: Sample mean and standard deviation of x7 x=m+s*randn(M,N);8 me=mean(x);9 se=std(x);

58 / 80

Scripts and Functions (Cont.)I You may call a function without using its output arguments.I Possible calls1 gauss(1,5,1,0.5);2 y=gauss(1,1e5,0,1);3 [y,mu,sigma]=gauss(1,1e5,0,1);4 [y,mu]=gauss(1,1e5,0,1);5 [y,˜,sigma]=gauss(1,1e5,0,1);

I You can create functions that have neither input or outputarguments. Type in a file plot results.m the codebelow:

1 function plot_results()2 % Plots Gauss signal3 plot(gauss(1,200,1,0.5),’ro’)4 axis([ 0 200 -3 4])5 xlabel(’Gaussian noise.’)

I Run this file at the command prompt:1 >> plot_results

59 / 80

Functions (Cont.)

I Function definitions inside functions are possible.

1 function a=rayleigh(N,s)2 [x, y]=boxmuller(N);3 a=s*sqrt(x.ˆ2+y.ˆ2);4

5 function [x1, x2]=boxmuller(M)6 u=rand(2,M);7 x1=sqrt(-2*log(u(1,:))).*cos(2*pi*u(1,:));8 x2=sqrt(-2*log(u(2,:))).*sin(2*pi*u(2,:));

I The function rayleigh is called primary.I The function boxmuller is called subfunction.I Subfunctions are only available to the primary function.I Function definitions inside functions are useful to shorten

repeated code segments.

60 / 80

Page 16: It has several advantages over high-level programming

Path Search and Browsing

I The current folder can be identified using pwd

1 pwd2 currentFolder = pwd

I Or via the current folder toolbar.

I Navigate to other using cd or the current folder toolbar.

61 / 80

Programming and Flow Control

Dr. Harris Tsimenidis

Newcastle UniversitySchool of Engineering

September 2018

62 / 80

Relational OperatorsI Relational operators perform element-by-element

comparisons between two arrays.I They return a logical array of the same size, with elements

set to logical 1 (true) where the relation is true, andelements set to logical 0 (false) where it is not.

I The operators <, >, <=, and >= use only the real part oftheir operands for the comparison.

I The operators == and ˜= test real and imaginary parts.

Relational Operator Description== Equal∌= Not equal< Less than> Greater than<= Less than or equal>= Greater than or equal

63 / 80

Relational OperatorsI Examples with real-valued variables:1 >> x=2;2 >> y=3;3 >> z=[x==y, x˜=y, x<y, x>y, x<=y, x>=y]4 z =5 0 1 1 0 1 06 >> whos7 Name Size Bytes Class Attributes8 x 1x1 8 double9 y 1x1 8 double

10 z 1x6 6 logical

I Note: z is of type logical and not double.I Comparison between scalar and a matrix:1 x=5; x>=[1 2 3; 4 5 6; 7 8 10]2 ans =3 1 1 14 1 1 05 0 0 0

64 / 80

Page 17: It has several advantages over high-level programming

Flow Control: if ExampleI Simple if structure (To be typed in a file and run via F5 or

via menu Debug/Run):

1 a=2; b=-3; c=5;2 Delta=bˆ2-4*a*c;3 if (Delta<0)4 disp(’Two complex-conjugate roots:’)5 x1=(-b+j*sqrt(-Delta))/(2*a);6 x2=(-b-j*sqrt(-Delta))/(2*a);7 end8 [x1; x2]

I After running, the following is displayed in the commandprompt:

1 Two complex-conjugate roots:2 ans =3 0.7500 + 1.3919i4 0.7500 - 1.3919i

65 / 80

Flow Control: if-else Example

I Generic if-else syntax:

1 if (condition statement)2 matlab commands3 ...4 else5 matlab commands6 ...7 end

66 / 80

Flow Control: if-else ExampleI Refined root computation:

1 a=1; b=3; c=2; Delta=bˆ2-4*a*c;2 if (Delta<0)3 disp(’Two complex-conjugate roots:’)4 x1=(-b+j*sqrt(-Delta))/(2*a);5 x2=(-b-j*sqrt(-Delta))/(2*a);6 else7 disp(’Two real-valued roots:’)8 x1=(-b+sqrt(Delta))/(2*a);9 x2=(-b-sqrt(Delta))/(2*a);

10 end11 [x1, x2]

I After running, the following is displayed in the commandprompt:

1 The polynomial has two real-valued roots:2 ans =3 -1 -2

67 / 80

Flow Control: if-elseif-else

I Generic syntax of the if-elseif-else structure:

1 if (condition statement)2 matlab commands3 ...4 elseif (condition statement)5 matlab commands6 ...7 elseif (condition statement)8 matlab commands9 ...

10 else11 matlab commands12 ...13 end

68 / 80

Page 18: It has several advantages over high-level programming

Flow Control: if-elseif-else Example

I Further refinement of root computation:

1 a=1; b=6; c=9; Delta=bˆ2-4*a*c;2 if (Delta<0)3 disp(’Two complex-conjugate roots:’)4 x1=(-b+j*sqrt(-Delta))/(2*a);5 x2=(-b-j*sqrt(-Delta))/(2*a);6 elseif (Delta>0)7 disp(’Two real-valued roots:’)8 x1=(-b+sqrt(Delta))/(2*a);9 x2=(-b-sqrt(Delta))/(2*a);

10 else11 disp(’Double real-valued root:’)12 x1=-b/(2*a);13 x2=x1;14 end15 [x1, x2]

69 / 80

Flow Control: if-elseif-else Example (Cont.)I After running, the following is displayed in the command

prompt:

1 Double real-valued root:2 ans =3 -3 -3

I Extend the algorithm further to handle the case a=0.I You can nest any number of if statements. Each if

statement requires an end keyword.I Avoid adding a space within the elseif keyword (else if).

The space creates a nested if statement that requires itsown end keyword.

I Within an if or while expression, all logical operators,including | and &, short-circuit.

I That is, if the first part of the expression determines a trueor false result, MATLAB does not evaluate the second partof the expression.

70 / 80

Flow Control: for

I Execute statements specified number of timesI Generic syntax for for:

1 for index = values2 matlab commands3 :4 end

I index can be

1 % initval:endval2 1:103 % initval:step:endval4 1:2:105 %valArray6 [1 5 7 12 20]

71 / 80

Flow Control: for (Cont.)

I To force an immediate exit of the loop, use a break orreturn statement.

I To skip the rest of the instructions in the loop, incrementthe loop counter, and begin the next iteration, use acontinue statement.

I Avoid assigning a value to the index variable within thebody of a loop. The for statement overrides any changesmade to the index within the loop.

I To iterate over the values of a single column vector, firsttranspose it to create a row vector.

72 / 80

Page 19: It has several advantages over high-level programming

Flow Control: for ExampleI Generate Td = 50 ms of fc = 1 kHz sinewave signals(t) = A sin(2πfct+φ) with fs = 48 kHz and random phase.

1 A=sqrt(2); % Amplitude2 fc=1000; % Carrier frequency in Hz3 Td=50e-3; % Duration in s4 fs=48000; % Sampling frequency5 Ts=1/fs; % Sampling time 1/fs6 phi=rand*2*pi; % Random phase [0 2*pi]7 N=Td*fs; % Length of the resulting vector8 t=zeros(1,N); % Pre-allocate memory9 s=zeros(1,N); % Pre-allocate memory

10 for n=1:N11 t(n)=(n-1)*Ts;12 s(n)=A*sin(2*pi*fc*t(n)+phi);13 end14 plot(t,s), grid on15 xlabel(’Time (ms)’)16 ylabel(’Amplitude (V)’)17 title(’Sampled sinusoid.’)

73 / 80

Flow Control: parfor

I Generic syntax for parfor:

1 matlabpool open2 ...3 parfor index = values4 matlab commands5 :6 end

I The loop occurs in parallel when you open a pool ofworkers.

I Unlike a traditional for-loop, iterations are not executed in aguaranteed order.

I Once the processor pool is open matlabpool open maybecommented out %.

I To close the pool use matlabpool close.

74 / 80

Flow Control: while

I Repeatedly execute statements while condition is trueI Generic syntax for while:

1 while expression2 matalb commands3 end

I An evaluated expression is true when the result isnon-empty and contains all non-zero elements (logical orreal numeric). Otherwise, the expression is false.

I Expressions can include relational operators,such as < or == and logical operators, such as &&, ||, or ˜.

I Careless programming may cause the expression to bealways 1. In such case, in order to interrupt the while looppress the following keyboard combination: Ctrl+C

75 / 80

Flow Control: while Example

I The previous example using a while loop

1 n=1;2 while (n<=N)3 t(n)=(n-1)*Ts;4 s(n)=A*sin(2*pi*fc*t(n)+phi);5 n=n+1;6 end

76 / 80

Page 20: It has several advantages over high-level programming

Working with Data Files

Dr. Harris Tsimenidis

Newcastle UniversitySchool of Engineering

September 2018

77 / 80

Data Files: .matI Use the save command to save the whole work space or

specific variables.I The default file name is matlab.mat1 >> x=gauss(1,1e5,0,1);2 >> y=rayleigh(1e5,1);3 >> save4 Saving to: matlab.mat

I Use the load command to load saved variables.1 >> clear2 >> whos3 >> load4 Loading from: matlab.mat

I You can also save only specific variables to a given filename:

1 save gauss_data.mat x

78 / 80

Data Files: .binI Data can also be saved/read in raw binary format using thefopen, fwrite and fread commands (similar to C/C++).

I To write data to a raw binary file using double precision:1 clear, x=gauss(1,1e5,0,1);2 % Open the file for writing (’wb’)3 fid=fopen(’results.bin’,’wb’);4 % Write matrix to file5 fwrite(fid, x,’double’);6 % Close file7 fclose(fid);

I To read the data from the previous binary file:1 % Open the file for reading (’rb’)2 fid=fopen(’results.bin’,’rb’);3 % Read matrix from file4 [x,count]=fread(fid,[1 inf],’double’);5 % Close file6 fclose(fid);

79 / 80

Data Files: .xlsxI Creating an xlsx file:1 values=1, 2, 3 ; 4, 5, ’x’ ; 7, 8, 9;2 headers=’First’, ’Second’, ’Third’;3 xlswrite(’myData.xlsx’, [headers; values]);

I Read data from the first worksheet into a numeric array:1 A=xlsread(’myData.xlsx’)

I Read a specific range of data:1 subsetA=xlsread(’myData.xlsx’, 1, ’B2:C3’)2 subsetA=3 2 34 5 NaN

I Read the second column:1 columnB=xlsread(’myExample.xlsx’, ’B:B’)2 columnB=3 24 55 8

80 / 80