introduction to matlab - newcastle university · dr. charalampos tsimenidis introduction to matlab...

80
Introduction to MATLAB Dr. Charalampos Tsimenidis Newcastle University School of Engineering September 2017 Dr. Charalampos Tsimenidis Introduction to MATLAB 1 /80

Upload: others

Post on 19-Jun-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Introduction to MATLAB

Dr. Charalampos Tsimenidis

Newcastle UniversitySchool of Engineering

September 2017

Dr. Charalampos Tsimenidis Introduction to MATLAB 1 /80

Page 2: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

MATLAB Advantages

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

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.Over 8000 functions available for various disciplines.At any time, variables (results of simulations) are stored inthe workspace for debugging and inspection,Excellent visualization (plots) capabilities,Easy programming, e.g. it is not required to define variabletypes (unless needed). All variables are usually of typedouble (64 bit or 8 byte representation).Quick code development.

Dr. Charalampos Tsimenidis Introduction to MATLAB 2 /80

Page 3: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

MATLAB Disadvantages

Very expensive for non students, although there are somefree clones, such as Octave or Scilab that are MATLABcompatible (but not 100%).Code execution can be slow if programmed carelesslywithout vectorization.Algorithms developed in MATLAB will need to be translatedin C, VHDL or assembly to be used in DSP or FPGAplatforms.

Dr. Charalampos Tsimenidis Introduction to MATLAB 3 /80

Page 4: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

The MATLAB IDE

Dr. Charalampos Tsimenidis Introduction to MATLAB 4 /80

Page 5: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

The MATLAB IDE: Command Window

The command window can be used to enter variables andperform simple computations:

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

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

Highest priority is from right to leftBrackets can be used to make priorities clear:

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

double is the default precisionformat long can be used to display more decimal points

Dr. Charalampos Tsimenidis Introduction to MATLAB 5 /80

Page 6: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

The MATLAB Editor

Scripts are files with .m extensions.

Newly created scripts names should not start with numbersor contain spaces.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 clearThey 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.

Dr. Charalampos Tsimenidis Introduction to MATLAB 6 /80

Page 7: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Online Help on the Command Prompt

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

To check how the help command works: >> help help

To check toolboxes available: >> help

To check the elementary math function toolbox: >> helpelfun

To check how the function fix works: >> help fix

To check functions available in the signal processingtoolbox: >> help signal

To check how the function fft works: >> help fft

Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80

Page 8: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

The MATLAB IDE: Command History

Command history window keep record of past commandprompt entries:

To recall past commands highlight and press F9Or directly drag and drop.SHIFT and CTRL keys can be used in conjunction to selecta block or more than one individual entries.Arrrow keys can be used to navigate through commandhistory entries.

Dr. Charalampos Tsimenidis Introduction to MATLAB 8 /80

Page 9: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

The MATLAB IDE: Workspace

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

Workspace associated MATLAB commands:

1 clear % or clear all2 who3 whos

Dr. Charalampos Tsimenidis Introduction to MATLAB 9 /80

Page 10: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Working with Scalar Variables

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

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

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

1 >> w=3;

Dr. Charalampos Tsimenidis Introduction to MATLAB 10 /80

Page 11: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Special Variable Names and Constants

ans: Most recent answer.pi: π = 3.141592653589793

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

Dr. Charalampos Tsimenidis Introduction to MATLAB 11 /80

Page 12: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Built-in Functions

There is a vast amount of built-in functions in Matlabranging from elementary mathematical functions to higherlevel.In contrast to other programming languages such as Cmost of the functions accept complex arguments and canbe effortlessly applied to vectors and matrices.To inspect what is available:

1 >> doc elfun2 >> doc specfun

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

1 >> help elfun

Dr. Charalampos Tsimenidis Introduction to MATLAB 12 /80

Page 13: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

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

Dr. Charalampos Tsimenidis Introduction to MATLAB 13 /80

Page 14: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Example: Mathematical Expressions

Input 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

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

Dr. Charalampos Tsimenidis Introduction to MATLAB 14 /80

Page 15: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Vector Arrays

Dr. Charalampos Tsimenidis

Newcastle UniversitySchool of Engineering

September 2017

Dr. Charalampos Tsimenidis Vector Arrays 15 /80

Page 16: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Vector Arrays

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

x =

a1a2. . .aM

or

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

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

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

Commas are optional.

Dr. Charalampos Tsimenidis Vector Arrays 16 /80

Page 17: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

The Colon Operator :

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

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

Non-unit spacing:

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

Dr. Charalampos Tsimenidis Vector Arrays 17 /80

Page 18: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

The Colon Operator : (Cont.)

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

Alternative: linspace

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

Dr. Charalampos Tsimenidis Vector Arrays 18 /80

Page 19: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Element-by-Element Vector Array Operations

Element-by-element multiplication .*

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

Element-by-element power .ˆ

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

Element-by-element division ./

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

Dr. Charalampos Tsimenidis Vector Arrays 19 /80

Page 20: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

min, max Functions

[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.[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

Dr. Charalampos Tsimenidis Vector Arrays 20 /80

Page 21: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

find and sort Functions

ind=find(X) finds the indices and values of nonzeroelements in X.

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

[B,IX]=sort(A,...) sorts the array elements of A. inascending or descending order.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

Dr. Charalampos Tsimenidis Vector Arrays 21 /80

Page 22: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

mean, var and std Functions

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

µx =1

N

N∑n=1

x(n)

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

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

Dr. Charalampos Tsimenidis Vector Arrays 22 /80

Page 23: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Plotting

Dr. Charalampos Tsimenidis

Newcastle UniversitySchool of Engineering

September 2017

Dr. Charalampos Tsimenidis Plotting 23 /80

Page 24: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

One-Dimensional Plots: The plot command

Check how the plot command works via help plot or docplotInitial 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

Dr. Charalampos Tsimenidis Plotting 24 /80

Page 25: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Line color, marker and line type

The default behaviour be controlled via an additionalargument 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

Dr. Charalampos Tsimenidis Plotting 25 /80

Page 26: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

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

Dr. Charalampos Tsimenidis Plotting 26 /80

Page 27: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

The plot command: Markers

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

Dr. Charalampos Tsimenidis Plotting 27 /80

Page 28: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

hold and grid

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

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

Dr. Charalampos Tsimenidis Plotting 28 /80

Page 29: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

The plot command: Two curves

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

Dr. Charalampos Tsimenidis Plotting 29 /80

Page 30: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

xlabel, ylabel, title, legend

Add axes labels and title1 xlabel(’time (s)’)2 ylabel(’Amplitude (V)’)3 title(’Gaussian distributed random noise signal.’)

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’)

The legend command requires as many string argumentsas the curves used in the plot command.The position of the legend can be controlled by anadditional argument, i.e. ’Location’ followed by a stringspecifying the actual location.Examples for location: ’North’, ’South’, ’East’, ’West’,’NorthEast’, ’NorthOutside’ ’NorthEastOutside’, ’Best’,’BestOutside’, etc.

Dr. Charalampos Tsimenidis Plotting 30 /80

Page 31: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Axes Control

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

1 axis([0 100 -4 6])

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])

Dr. Charalampos Tsimenidis Plotting 31 /80

Page 32: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Multiple Figures and Subplots

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

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

Subplots in the same figure can be created viasubplot(mnk), where m, n and k are integers.The pair m, n gives the size of the array of plots to begenerated, while k is used to index the plots.k=1 corresponds to the upper-left plot. k=m*ncorresponds to the lower-right plot.Plots are indexed row-wise for increasing k. If the indexk>n, a new row of plots starts.

Dr. Charalampos Tsimenidis Plotting 32 /80

Page 33: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Subplot Example

1 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

Dr. Charalampos Tsimenidis Plotting 33 /80

Page 34: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Other Plot Types

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

Dr. Charalampos Tsimenidis Plotting 34 /80

Page 35: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Working with Array Variables

Dr. Charalampos Tsimenidis

Newcastle UniversitySchool of Engineering

September 2017

Dr. Charalampos Tsimenidis Working with Array Variables 35 /80

Page 36: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Arrays: Vectors and Matrices

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

x =

a1a2. . .aM

or

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

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

A =

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

A scalar variable is a 1× 1 arrayMatrix and vector indexing starts in Matlab with 1.

Dr. Charalampos Tsimenidis Working with Array Variables 36 /80

Page 37: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Entering Arrays

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

Elements on the same row are separated by space orcomma.New line is started with semicolon.

Dr. Charalampos Tsimenidis Working with Array Variables 37 /80

Page 38: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Array Indexing

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

end can be used for the last elements:

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

Dr. Charalampos Tsimenidis Working with Array Variables 38 /80

Page 39: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Array Indexing using :

To address the full column of a matrix:

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

To address the full row of a matrix:

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

Dr. Charalampos Tsimenidis Working with Array Variables 39 /80

Page 40: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Value Assignment on Array Elements

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

Multiple elements can be assigned at once:

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

Dr. Charalampos Tsimenidis Working with Array Variables 40 /80

Page 41: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Array Concatenation

Arrays can be concatenated by using the [] operator.However, this can be inefficient and time consuming forlarge 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

Dr. Charalampos Tsimenidis Working with Array Variables 41 /80

Page 42: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Deleting Array Rows or Columns

Deleting rows:

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

Deleting columns:

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

Dr. Charalampos Tsimenidis Working with Array Variables 42 /80

Page 43: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Matrix and Vector Sizes

The length of a vector can be checked via the lengthcommand:

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

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

Dr. Charalampos Tsimenidis Working with Array Variables 43 /80

Page 44: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Elementary Array Generating Functions

Matlab provides several functions that generate basic matrices:zeros(M,N) and ones(M,N)

rand(M,N) generates random numbers uniformlydistributed between [0, 1]:randn(M,N) generates random numbers that areGaussian distributed with mean 0 and standard deviation 1randi([IMIN,IMAX],M,N) generates random integernumbers from a uniform discrete distributioneye() generates the identity matrix:

Dr. Charalampos Tsimenidis Working with Array Variables 44 /80

Page 45: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Vector and Matrix Operations

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

Dr. Charalampos Tsimenidis Working with Array Variables 45 /80

Page 46: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Transpose Operator

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

Dr. Charalampos Tsimenidis Working with Array Variables 46 /80

Page 47: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Transpose Operator (Cont.)

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

Dr. Charalampos Tsimenidis Working with Array Variables 47 /80

Page 48: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Array Addition/Subtraction

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

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

Dr. Charalampos Tsimenidis Working with Array Variables 48 /80

Page 49: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Array Multiplication

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.

Dr. Charalampos Tsimenidis Working with Array Variables 49 /80

Page 50: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Array Multiplication (Cont.)

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

Dr. Charalampos Tsimenidis Working with Array Variables 50 /80

Page 51: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Matrix Division

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

Dr. Charalampos Tsimenidis Working with Array Variables 51 /80

Page 52: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Matrix Power and Inverse

Power of a matrix:

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

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

Dr. Charalampos Tsimenidis Working with Array Variables 52 /80

Page 53: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Matrix Inverse (Cont.)

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

Dr. Charalampos Tsimenidis Working with Array Variables 53 /80

Page 54: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Scripts and Functions

Dr. Charalampos Tsimenidis

Newcastle UniversitySchool of Engineering

September 2017

Dr. Charalampos Tsimenidis Scripts and Functions 54 /80

Page 55: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Scripts and Functions

Scripts and functions are files with .m extensions.Newly created scripts and functions names should notstart with numbers or contain spaces.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 fft.Scripts execute the MATLAB commands found in the file.Scripts have no input or output variables.To create a script from the command prompt: >> editfilename.m

Alternatively, you can use the corresponding toolbar iconor the new file menu entry.Variables created by a script are available in theworkspace.

Dr. Charalampos Tsimenidis Scripts and Functions 55 /80

Page 56: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Scripts and Functions (Cont.)

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

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

Comments about the function usage can be put after thefunction declaration for clarity.The MATLAB functionality can be extended by creatingnew functions to solve a specific problem.

Dr. Charalampos Tsimenidis Scripts and Functions 56 /80

Page 57: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Function Example

The following code creates a new MATLAB function thatgenerates 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);

Type >> help gauss to see the output message.To run the function gauss:

1 >> y=gauss(1,1e5,0,1);2 >> [mean(y), std(y)]3 ans =4 -0.0003 0.9997

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

Dr. Charalampos Tsimenidis Scripts and Functions 57 /80

Page 58: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Scripts and Functions (Cont.)

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

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);

Dr. Charalampos Tsimenidis Scripts and Functions 58 /80

Page 59: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Scripts and Functions (Cont.)

You may call a function without using its output arguments.Possible calls

1 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);

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.’)

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

Dr. Charalampos Tsimenidis Scripts and Functions 59 /80

Page 60: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Functions (Cont.)

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,:));

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

Dr. Charalampos Tsimenidis Scripts and Functions 60 /80

Page 61: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Path Search and Browsing

The current folder can be identified using pwd

1 pwd2 currentFolder = pwd

Or via the current folder toolbar.

Navigate to other using cd or the current folder toolbar.

Dr. Charalampos Tsimenidis Scripts and Functions 61 /80

Page 62: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Programming and Flow Control

Dr. Charalampos Tsimenidis

Newcastle UniversitySchool of Engineering

September 2017

Dr. Charalampos Tsimenidis Programming and Flow Control 62 /80

Page 63: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Relational Operators

Relational operators perform element-by-elementcomparisons between two arrays.They return a logical array of the same size, with elementsset to logical 1 (true) where the relation is true, andelements set to logical 0 (false) where it is not.The operators <, >, <=, and >= use only the real part oftheir operands for the comparison.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

Dr. Charalampos Tsimenidis Programming and Flow Control 63 /80

Page 64: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Relational Operators

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

Note: z is of type logical and not double.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

Dr. Charalampos Tsimenidis Programming and Flow Control 64 /80

Page 65: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Flow Control: if Example

Simple if structure (To be typed in a file and run via F5 orvia 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]

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

Dr. Charalampos Tsimenidis Programming and Flow Control 65 /80

Page 66: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Flow Control: if-else Example

Generic if-else syntax:

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

Dr. Charalampos Tsimenidis Programming and Flow Control 66 /80

Page 67: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Flow Control: if-else Example

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]

After running, the following is displayed in the commandprompt:

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

Dr. Charalampos Tsimenidis Programming and Flow Control 67 /80

Page 68: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Flow Control: if-elseif-else

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

Dr. Charalampos Tsimenidis Programming and Flow Control 68 /80

Page 69: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Flow Control: if-elseif-else Example

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]

Dr. Charalampos Tsimenidis Programming and Flow Control 69 /80

Page 70: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Flow Control: if-elseif-else Example (Cont.)

After running, the following is displayed in the commandprompt:

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

Extend the algorithm further to handle the case a=0.You can nest any number of if statements. Each ifstatement requires an end keyword.Avoid adding a space within the elseif keyword (else if).The space creates a nested if statement that requires itsown end keyword.Within an if or while expression, all logical operators,including | and &, short-circuit.That is, if the first part of the expression determines a trueor false result, MATLAB does not evaluate the second partof the expression.

Dr. Charalampos Tsimenidis Programming and Flow Control 70 /80

Page 71: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Flow Control: for

Execute statements specified number of timesGeneric syntax for for:

1 for index = values2 matlab commands3 :4 end

index can be

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

Dr. Charalampos Tsimenidis Programming and Flow Control 71 /80

Page 72: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Flow Control: for (Cont.)

To force an immediate exit of the loop, use a break orreturn statement.To skip the rest of the instructions in the loop, incrementthe loop counter, and begin the next iteration, use acontinue statement.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.To iterate over the values of a single column vector, firsttranspose it to create a row vector.

Dr. Charalampos Tsimenidis Programming and Flow Control 72 /80

Page 73: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Flow Control: for Example

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.’)

Dr. Charalampos Tsimenidis Programming and Flow Control 73 /80

Page 74: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Flow Control: parfor

Generic syntax for parfor:

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

The loop occurs in parallel when you open a pool ofworkers.Unlike a traditional for-loop, iterations are not executed in aguaranteed order.Once the processor pool is open matlabpool open maybecommented out %.To close the pool use matlabpool close.

Dr. Charalampos Tsimenidis Programming and Flow Control 74 /80

Page 75: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Flow Control: while

Repeatedly execute statements while condition is trueGeneric syntax for while:

1 while expression2 matalb commands3 end

An evaluated expression is true when the result isnon-empty and contains all non-zero elements (logical orreal numeric). Otherwise, the expression is false.Expressions can include relational operators,such as < or == and logical operators, such as &&, ||, or ˜.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

Dr. Charalampos Tsimenidis Programming and Flow Control 75 /80

Page 76: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Flow Control: while Examples

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

Using the time duration as control expression:

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

Dr. Charalampos Tsimenidis Programming and Flow Control 76 /80

Page 77: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Working with Data Files

Dr. Charalampos Tsimenidis

Newcastle UniversitySchool of Engineering

September 2017

Dr. Charalampos Tsimenidis Working with Data Files 77 /80

Page 78: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Data Files: .mat

Use the save command to save the whole work space orspecific variables.The default file name is matlab.mat

1 >> x=gauss(1,1e5,0,1);2 >> y=rayleigh(1e5,1);3 >> save4 Saving to: matlab.mat

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

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

1 save gauss_data.mat x

Dr. Charalampos Tsimenidis Working with Data Files 78 /80

Page 79: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Data Files: .bin

Data can also be saved/read in raw binary format using thefopen, fwrite and fread commands (similar to C/C++).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);

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);

Dr. Charalampos Tsimenidis Working with Data Files 79 /80

Page 80: Introduction to MATLAB - Newcastle University · Dr. Charalampos Tsimenidis Introduction to MATLAB 7 /80. The MATLAB IDE: Command History Command history window keep record of past

Data Files: .xlsx

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]);

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

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

Read the second column:1 columnB=xlsread(’myExample.xlsx’, ’B:B’)2 columnB=3 24 55 8 Dr. Charalampos Tsimenidis Working with Data Files 80 /80