Download presentation
Presentation is loading. Please wait.
Published bySteven Watkins Modified over 7 years ago
1
An Introduction to MATLAB M File, Simulink and GUI
Dr. Mohamed Ibrahim
2
Introduction to MATLAB and Simulink
What can you gain from the course ? Know what M File/Simulink/GUI is Know how to get started with M File/Simulink/GUI Know basics of M File/Simulink/GUI know how to solve simple problems Know how to built application (Fuzzy Controller)
3
Simmilation Package Circuit Analysis Saber Pspice Finite Element Ansys
Control Orientation Matlab Lab View Why Matlab? User Friendly (GUI) Easy to work with Powerful tools for complex mathematics
4
Introduction to MATLAB
Contents M File Introduction Math Function Vectors and Matrices Built in functions M–files : script and/functions Symbolic Control Signal processing Image Hardware Examples Application GUI Components Examples Application Simulink Components Modeling examples Application
5
History MATLAB – MATrix LABoratory
In 1970s – Dr.Cleve Moler Based on Fortran on EISPACK and LINPACK Only solve basic matrix calculation and graphic 1984 – MathWorks Company by Cleve Moler and Jack Little Matlab 1.0 based on C Included image manipulations, multimedia etc. toolboxes In 1990 – run on Windows Simulink, Notebook, Symbol Operation, etc. 21 Century
6
Files in the working Folder
Getting Started Run MATLAB from Start Programs MATLAB Depending on version used, several windows appear For example in (R2011b), there are several windows – command history, command, workspace, etc Command History Workspace Command Window Files in the working Folder
7
Ask more information about software
contacting the company eg. Technique support, bugs. >> ver version of matlab and its toolboxes licence number >> whatsnew what’s new of the version
8
• Where to get help? 1) In MATLAB’s prompt type: help lookfor helpwin
helpdesk demos. 2) On the Web:
9
MATLAB’s Workspace Data files save filename var1 var2 … load filename
• who,whos - current variables in workspace • save - save workspace variables to *.mat file • load - load variables from *.mat file • clear all - clear workspace variables Data files save filename var1 var2 … >> save myfile.mat x y binary >> save myfile.dat x –ascii ascii load filename >> load myfile.mat binary >> load myfile.dat –ascii ascii
10
Special Values pi: value up to 15 significant digits i, j: sqrt(-1)
Inf: infinity (such as division by 0) NaN: Not-a-Number (division of zero by zero) clock: current date and time in the form of a 6-element row vector containing the year, month, day, hour, minute, and second date: current date as a string such as 16-Feb-2004 eps: epsilon is the smallest difference between two numbers ans: stores the result of an expression ; surpress output , separation of commands in one line
11
Special command help command Online help
lookfor keyword Lists related commands which Version and location info clear Clears the workspace clc Clears the command window diary filename Sends output to file diary on/off Turns diary on/off who, whos Lists content of the workspace more on/off Enables/disables paged output Ctrl+c Aborts operation … Continuation % Comments
12
Basic Operations variable_name = expression; addition a + b a + b
subtraction a - b a - b multiplication a x b a * b division a / b a / b exponent ab a ^ b
13
Working with complex numbers
real and imaginary real % real part of complex number imag % imaginary part of complex number magnitude and phase abs % magnitude of complex number angle % phase of complex number Examples during Matlab demo
14
Built in functions (commands)
Scalar functions – used for scalars and operate element-wise when applied to a matrix or vector e.g. sin cos tan atan asin log abs angle sqrt round floor At any time you can use the command help to get help e.g. >>>help sin
15
Built in functions (commands)
>>> a=linspace(0,(2*pi),10) a = Columns 1 through 7 Columns 8 through 10 >>> b=sin(a) b = Columns 1 through 7 Columns 8 through 10 >>>
16
Built in functions (commands)
Vector functions – operate on vectors returning scalar value e.g. max min mean prod sum length >>> a=linspace(0,(2*pi),10) >>> b=sin(a); >>> max(b) ans = 0.9848 >>> max(a) 6.2832 >>> length(a) 10
17
Data >> A=[ 2 5 8 9 6 7] A = 2 5 8 9 6 7 >> x=1:2:10 x =
[x1 x2 … ; x3 x4 …] input of matrices and vectors x1:x2 creation of a line vector [x1 x1+1 x1+2…x2] x1:d:x2 creation of a line vector [x1 x1+d x1+2*d…x2] linspace(x1,x2,n) line vector, start val x1, end val x2, size n, equally distributed logspace(x1,x2,n) line vector, start val x1, end val x2, size n, logarithmically distributed >> A=[ ] A = >> x=1:2:10 x =
18
How do we assign values to vectors?
Vectors and Matrices How do we assign values to vectors? If we want to construct a vector of, say, 100 elements between 0 and 2 – linspace >>> c1 = linspace(0,(2*pi),100); >>> whos Name Size Bytes Class c x double array Grand total is 100 elements using 800 bytes >>>
19
How do we assign values to vectors?
Vectors and Matrices How do we assign values to vectors? If we want to construct an array of, say, 100 elements between 0 and 2 – colon notation >>> c2 = (0:0.0201:2)*pi; >>> whos Name Size Bytes Class c x double array c x double array Grand total is 200 elements using 1600 bytes >>>
20
Built-in MATLAB Functions
result = function_name( input ); abs, sign log, log10, log2 exp sqrt sin, cos, tan/sind,cosd,tand asin, acos, atan max, min round, floor, ceil, fix mod, rem Real,imag,abs,angle >>> help elmat help for elementary math functions
21
Basic Operations on Matrices
• All the operators in MATLAB defined on matrices : +, -, *, /, ^, sqrt, sin, cos etc. • Element wise operators defined with preceding dot : .*, ./, .^ . • size(A) - size vector • sum(A) - columns sums vector • sum(sum(A)) - all the elements sum
22
Basic Mathematical Operations
Addition: >> C = A + B Subtraction: >> D = A – B Multiplication: >> E = A * B (Matrix multiplication) >> E = A .* B (Element wise multiplication) Division: Left Division and Right Division >> F = A . / B (Element wise division) >> F = A / B (A * inverse of B) >> F = A . \ B (Element wise division) >> F = A \ B (inverse of A * B) Examples during Matlab demo
23
Built-in MATLAB Functions
eye(n) nxn identity matrix ones(n) nxn matrix with all entries equal to 1 zeros(n) nxn matrix with all entries equal to 0 rand(x) nxn matrix with random entries between 0 and 1 randn(x) nxn matrix with normally distributed random entries magic(x) nxn matrix constructed from the integers 1 through n^2 with equal row and column sums min, max, mean, std, sum, prod ,Diag Inv, Det, Eig, Rank, Cumsum, Cumprod matrix .’, matrix ’, diff, conv Size, length >>> help matfun
24
Built-in MATLAB Functions
min, max, mean, std, sum, prod ,Diag Inv, Det, Eig, Rank, Cumsum, Cumprod matrix .’, matrix ’, diff, conv
25
Changing the data format
>> value = ; format short format long format short e e+001 format long e e+001 format short g format long g format rat 1000/81
26
Matrices in Matlab To enter a matrix >> A = [3 1 ; 6 4]
3 1 6 4 >> A = [3 1 ; 6 4] >> A = [3, 1 ; 6, 4] >> B = [3, 5 ; 0, 2] Examples during Matlab demo
27
How do we assign values to matrices ?
Vectors and Matrices How do we assign values to matrices ? >>> A=[1 2 3;4 5 6;7 8 9] A = >>> Columns separated by space or a comma Rows separated by semi-colon
28
Generating basic matrices
Matrix with ZEROS: >> Z = ZEROS (r, c) Matrix with ONES: >> O = ONES (r, c) IDENTITY Matrix: >> I = EYE (r, c) r Rows c Columns zeros, ones, eye Matlab functions Examples during Matlab demo
29
Variables – Vectors and Matrices –
ALL variables are matrices Variables They are case–sensitive i.e x X Their names can contain up to 31 characters Must start with a letter e.g x x x x 4 Variables are stored in workspace
30
How do we assign values to vectors?
Vectors and Matrices How do we assign values to vectors? A row vector – values are separated by spaces >>> A = [ ] A = >>> >>> B = [10;12;14;16;18] B = 10 12 14 16 18 >>> A column vector – values are separated by semi–colon (;)
31
How do we assign values to matrices ?
Vectors and Matrices How do we assign values to matrices ? >>> A=[1 2 3;4 5 6;7 8 9] A = >>> Columns separated by space or a comma Rows separated by semi-colon
32
How do we access elements in a matrix or a vector?
Vectors and Matrices How do we access elements in a matrix or a vector? Try the followings: >>> A(2,3) ans = 6 >>> A(:,3) ans = 3 6 9 >>> A(2,:) ans = >>> A(1,:) ans =
33
Arithmetic operations – Matrices
Vectors and Matrices Arithmetic operations – Matrices Performing operations to every entry in a matrix Add and subtract >>> A=[1 2 3;4 5 6;7 8 9] A = >>> >>> A+3 ans = >>> A-2 ans =
34
Arithmetic operations – Matrices
Vectors and Matrices Arithmetic operations – Matrices Performing operations to every entry in a matrix Multiply and divide >>> A=[1 2 3;4 5 6;7 8 9] A = >>> >>> A*2 ans = >>> A/3 ans =
35
Arithmetic operations – Matrices
Vectors and Matrices Arithmetic operations – Matrices Performing operations to every entry in a matrix Power >>> A=[1 2 3;4 5 6;7 8 9] A = >>> To square every element in A, use the element–wise operator .^ >>> A.^2 ans = >>> A^2 ans = A^2 = A * A
36
Arithmetic operations – Matrices
Vectors and Matrices Arithmetic operations – Matrices Performing operations between matrices >>> A=[1 2 3;4 5 6;7 8 9] A = >>> B=[1 1 1;2 2 2;3 3 3] B = = A*B = A.*B
37
? (matrices singular) Arithmetic operations – Matrices
Vectors and Matrices Arithmetic operations – Matrices Performing operations between matrices ? (matrices singular) A/B = A./B
38
Arithmetic operations – Matrices
Vectors and Matrices Arithmetic operations – Matrices Performing operations between matrices ??? Error using ==> ^ At least one operand must be scalar A^B = A.^B
39
Vectors and Matrices Ex 1.1 Solve the following Equation 4x1 - 2x2 - 10x3=-10 2x1 + 10x2- 12x3=32 -4x1- 6x2 + 16x3=-10 For the matrix equation below, AX = B, determine the vector X.
40
Vectors and Matrices solution a=[ ; ; ]; b=[-10;32;-10]; c=inv(a); z=c*b; x1=z(1) x2=z(2) x3=z(3) x1 = x2 = x3 =
41
Arithmetic operations – Matrices
Vectors and Matrices Arithmetic operations – Matrices Example: -j5 j10 10 1.50o 2-90o Solve for V1 and V2
42
Arithmetic operations – Matrices
Vectors and Matrices Arithmetic operations – Matrices Example (cont) (0.1 + j0.2)V1 – j0.2V = -j2 - j0.2V j0.1V = 1.5 = A x y =
43
Arithmetic operations – Matrices
Vectors and Matrices Arithmetic operations – Matrices Example (cont) >>> A=[( j) -0.2j;-0.2j 0.1j] A = i i i i >>> y=[-2j;1.5] y = i 1.5000 >>> x=A\y x = i i >>> * A\B is the matrix division of A into B, which is roughly the same as INV(A)*B *
44
Arithmetic operations – Matrices
Vectors and Matrices Arithmetic operations – Matrices Example (cont) >>> V1= abs(x(1,:)) V1 = >>> V1ang= angle(x(1,:)) V1ang = 0.5191 V1 = 16.1229.7o V
45
Built in functions (commands)
Matrix functions – perform operations on matrices >>> x*xinv ans = >>> >>> x=rand(4,4) x = >>> xinv=inv(x) xinv =
46
Built in functions (commands)
From our previous example, = y x A = >>> x=inv(A)*y x = i i
47
Polynomial Example 1.1 Find the roots of the following polynomial.
s6 + 9s s s s s + 15 The polynomial coefficients are entered in a row vector in descending powers. The roots are found using roots. p = [ ] r = roots(p) i i i i
48
The coefficients of the polynomial equation
Example 1.2 The roots of a polynomial are i i i i . Determine the polynomial equation. Complex numbers may be entered using function i or j. The roots are then entered in a column vector. The polynomial equation is obtained using poly as follows i = sqrt(-1) r = [ *i -1-2*I 0.5*i -0.5*i ] p = poly(r) The coefficients of the polynomial equation
49
Find a polynomial of degree 3 to fit the following data
Example 1.3 Find a polynomial of degree 3 to fit the following data x = [ ]; y = [ ]; c = polyfit(x,y,3) x y
50
Partial Fraction a=[2 0 9 1] b=[1 1 4 4 ] [r,p,k]=residue(a,b) Example
Determine the partial fraction expansion for a=[ ] b=[ ] [r,p,k]=residue(a,b) r = i i p = i i k = 2
51
Plotting / displaying 3D plots: PLOT(x,y) IMAGE(x) MESH MESHGRID
Plots y versus x. Linear plot XLABEL(‘label’) YLABEL(‘label’) TITLE(‘title’) IMAGE(x) Displays image 3D plots: MESH 3D mesh surface (Ex. filters) MESHGRID Useful in 3D plots SURF 3D colored surface (Ex. filters) Examples during Matlab demo
52
Built in functions (commands)
Data visualisation – plotting graphs >>> help graph2d >>> help graph3d e.g. plot polar loglog mesh semilog plotyy surf Visualization and Graphics • plot(x,y), plot(x,sin(x)) - plot 1-D function • figure , figure(k) - open a new figure • hold on, hold off - refreshing • mesh(x_ax,y_ax,z_mat) - view surface • contour(z_mat) - view z as top. map • subplot(3,1,2) - locate several plots in figure • axis([xmin xmax ymin ymax]) - change axes • title(‘figure title’) - add title to figure
53
Example 1 Fit a polynomial of order 2 to the following data Plot the given data point with symbol x, and the fitted curve with a solid line. Place a boxed legend on the graph. The command p = polyfit(x, y, 2) is used to find the coefficients of a polynomial of degree 2 that fits the data, and the command yc = polyval(p, x) is used to evaluate the polynomial at all values in x. We use the following command. x=[ ] y=[ ]
54
x=[ ] y=[ ] p = polyfit(x,y,2) yc=polyval(p,x) plot(x,y,'r*',x,yc) title('graph title') xlabel('xlable') ylabel('ylable') grid legend('point','curve',4)
55
Data visualisation – plotting graphs
Example on plot – 2 dimensional plot title xlabel ylabel legend Use ‘copy’ and ‘paste’ to add to your window–based document, e.g. MSword Example Plot sine wave from –pi to pi and write on axis '-pi','-pi/2','0','pi/2','pi'
56
x = -pi:.1:pi; y = sin(x); plot(x,y) set(gca,'XTick',-pi:pi/2:pi) set(gca,'XTickLabel',{'-pi','-pi/2','0','pi/2','pi'}) xlabel('-\pi \leq \Theta \leq \pi') ylabel('sin(\Theta)') title('Plot of sin(\Theta)') text(-pi/4,sin(-pi/4),'\leftarrow sin(-\pi\div4)',... 'HorizontalAlignment','left')
57
Multi Figures x = -pi:.1:pi; y = sin(x); subplot(2,3,1),plot(x,y)
58
MATLAB supports many types of graph and surface plots:
line plots (x vs. y), filled plots, bar charts, pie charts, parametric plots, polar plots, contour plots, density plots, log axis plots, surface plots, parametric plots in 3 dimensions and spherical plots.
59
Z = 10e(–0.4a) sin (2ft) for f = 2
Data visualisation – plotting graphs Example on mesh and surf – 3 dimensional plot Supposed we want to visualize a function Z = 10e(–0.4a) sin (2ft) for f = 2 when a and t are varied from 0.1 to 7 and 0.1 to 2, respectively >>> [t,a] = meshgrid(0.1:.01:2, 0.1:0.5:7); >>> f=2; >>> Z = 10.*exp(-a.*0.4).*sin(2*pi.*t.*f); >>> surf(Z); >>> figure(2); >>> mesh(Z);
60
Built in functions (commands)
Data visualisation – plotting graphs Example on mesh and surf – 3 dimensional plot
61
Built in functions (commands)
eg3_srf.m Data visualisation – plotting graphs Example on mesh and surf – 3 dimensional plot [x,y] = meshgrid(-3:.1:3,-3:.1:3); z = 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ... - 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ... - 1/3*exp(-(x+1).^2 - y.^2); surf(z);
62
Built in functions (commands)
Data visualisation – plotting graphs Example on mesh and surf – 3 dimensional plot
63
plot, stairs, bar (…), stem, Loglog, Semilogx, Semilogy,
polar, fplot, ezplot, ezplot, subplot
64
Flow Control • MATLAB has five flow control constructs: – for loops
– if statements –switch statements –while loops – break statements
65
Logical Conditions • == , < , > , (not equal)~= ,(not)~
• find(‘condition’) - Returns indexes of A’s elements that satisfies the condition. >> A = [1 2; 3 4], I = find(A<4) A = 1 2 3 4 I = 1 2 3
66
for % Example: • FOR Repeat statements a specific number of times.
• The general form of a FOR statement is: FOR variable = expr, statement, ..., END % Example: N=5 for I = 1:N for J = 1:N A(I,J) = 1/(I+J-1); end
67
IF • IF statement condition. The general form of the IF statement is
IF expression statements ELSEIF expression ELSE END
68
Example for I=1:4 for J=1:4 if I == J A(I,J) = 2 elseif abs(I-J) == 1
end A
69
switch • SWITCH - Switch among several cases based on expression.
• The general form of the SWITCH statement is: SWITCH switch_expr CASE case_expr, statement, ..., statement CASE {case_expr1, case_expr2, case_expr3,...} ... OTHERWISE, END
70
Example a=input('enter value for a') x=2; y=5; switch a case 1 u=x+y
end
71
while • WHILE Repeat statements an indefinite number of times.
• The general form of a WHILE statement is: WHILE expression statements END
72
Example
73
M-files : Script and function files
When problems become complicated and require re–evaluation, entering command at MATLAB prompt is not practical Solution : use M-files Script Function Collections of commands Executed in sequence when called Saved with extension “.m” User defined commands Normally has input & output Saved with extension “.m”
74
At Matlab prompt type in edit to invoke M-file editor
M-files : script and function files (script) eg1_plt.m At Matlab prompt type in edit to invoke M-file editor Save this file as test1.m
75
To run the M-file, type in the name of the file at the prompt e. g
To run the M-file, type in the name of the file at the prompt e.g >>> test1 It will be executed provided that the saved file is in the known path Type in matlabpath to check the list of directories listed in the path Use path editor to add the path: File Set path …
76
Write an m–file to plot I and versus frequency for R =10, C = 100 uF,
Example – RLC circuit + V – R = 10 C L Write an m–file to plot I and versus frequency for R =10, C = 100 uF, L = 0.01 H.
77
Example – RLC circuit C=1e-4 L=0.01 R=10 V=220*sqrt(2) for W=1:50000
XC=1/(W*C); XL=W*L; Z=sqrt(R^2+(XL-XC)^2); I(W)=V/Z; end W=1:5000 plot(W,I(W)) grid title('Current with Frequency') ylabel('Current(Amp)') xlabel('Frequency(Hz)')
78
Example – RLC circuit
79
M-files : script and function files (function)
Function is a ‘black box’ that communicates with workspace through input and output variables. INPUT FUNCTION OUTPUT – Commands – Functions – Intermediate variables
80
M-files : script and function files (function)
Every function must begin with a header: function output=function_name(inputs) Output variable Must match the file name input variable
81
Function File Stat.m %This function calculate the Mean and Root Mean Square function [mean,RMS] = stat(x) n = length(x); mean = sum(x)/n; RMS = sqrt(sum(x.*x)/n); Script File calc.m x=[1:20] [mean,RMS] = stat(x) mean RMS >> help stat This function calculate the Mean and Root Mean Square
82
Ex IM Control 1- AC Voltage Control 2-V/F control speed_torque.m
function a=speed_torque(r1,l1,r2,l2,f,p,v) w=2*pi*f ns=120*f/p for k=1:100 s=1-k/100 nr=ns*(1-s) i=((v)/(sqrt((r1+r2/s)^2+(w*l1+w*l2)^2))) T=((3*i*i*r2/s)/(2*pi*ns/60)) plot(nr,T,'b+:') hold on end
83
IM_Control.m p=4 l1=0.0001565 l2=0.0001777 r1=0.029 r2=.059 f=60 v=100
speed_torque(r1,l1,r2,l2,f,p,v) v=200 v=300 f=30 v=150 f=20
84
Example contains read and write
i=sqrt(-1) R=input('Enter R: '); C=input('Enter C: '); L=input('Enter L: '); w=input('Enter w: '); R2=R*R X=(w*L-1/(w*C)) z=(R+X*i) Mag = abs(z) Phase = angle(z) fprintf('\n The magnitude of the impedance at %.1f rad/s is %.3f ohm\n', w,Mag); fprintf('\n The angle of the impedance at %.1f rad/s is %.3f degrees\n\n', w, Phase);
85
Classical Control In Matlab
86
Classical Control Classical Control Transfer Function Step Response
Root Locus Bode Diagram Nyquist Plot
87
Transfer Function >> G=tf([1],[1 2 5]) Transfer function: 1
s^2 + 2 s + 5
88
Step Response >> G=tf([1],[1 2 5]) Transfer function: 1
s^2 + 2 s + 5 >> step(G)
89
Root Locus Diagram >> G=tf([1 1],[1 2 5]) Transfer function:
s^2 + 2 s + 5 >> rlocus(G)
90
Bode Plot >> G=tf([1 1],[1 2 5]) Transfer function: s + 1
s^2 + 2 s + 5 >> bode(G) >> grid
91
Nyquist Plot >> G= tf([2 5 1],[1 2 3]) Transfer function:
2 s^2 + 5 s + 1 s^2 + 2 s + 3 >> nyquist(G) >> grid
92
PID Controller G_num=[5] G_den=[1 2 5] G=tf(G_num,G_den) H=[-1]
kp=4; ki=50; kd=1 pid_num=[kd kp Ki] pid_den=[1 0]; [num,den]=cloop(conv(G_num,pid_num),conv(G_den,pid_den),H); closed_Loop=tf(num,den) step(G,'r') hold on step(closed_Loop,'b') legend('Open Loop','Closed Loop') grid on
93
Symbolic Calculus Linear Algebra Simplification – Equation Solutions
Symbolic mathematics deals with equations before you plug in the numbers. Calculus integration, differentiation, Taylor series expansion, … Linear Algebra inverses, determinants, eigenvalues, … Simplification – algebraic and trigonometric expressions Equation Solutions algebraic and differential equations Transforms Fourier, Laplace, Z transforms and inverse transforms, …
94
Equation Solutions syms a b c x eq=a*x^2+b*x+c [x]=solve(eq) x =
-(b + (b^2 - 4*a*c)^(1/2))/(2*a) -(b - (b^2 - 4*a*c)^(1/2))/(2*a) subs(eq,2) ans = 4*a + 2*b + c
95
Differentiation & Integration
clear syms m x b th n y y = m*x + b diff(y, x) diff(y, b) clear syms m x b th n y y = m*x + b int(y, x) int(y, b)
96
Linear Algebra syms a l r w a=[w*l r;-r w*l] inv(a)
[ (l*w)/(l^2*w^2 + r^2), -r/(l^2*w^2 + r^2)] [ r/(l^2*w^2 + r^2), (l*w)/(l^2*w^2 + r^2)]
97
Transformation syms x y v n t z w s %Laplace Transform
x=laplace(3*t^3) %Z Transform y=ztrans(2^n) %Fourrier Transform v=fourier(exp(-5*abs(t))) % Inverse Laplace Transform x=ilaplace(18/s^4) %Inverse Z Transform y=iztrans(z/(z - 2)) %Inverse Fourrier Transform v=ifourier(1/w)
98
Matlab with Hardware Serial Port Parallel Port Sound Card Camera
99
Serial Port Example: % To construct a serial port object:
s1 = serial('COM1', 'BaudRate', 1200); % To connect the serial port object to the serial port: fopen(s1) % To query the device. fprintf(s1, ‘Moh'); data= fscanf(s1); % To disconnect the serial port object from the serial port. fclose(s1);
100
Parallel Port % Create a Digital I/O Object with the digitalio function dio=digitalio('parallel',‘lpt1'); %Add lines to a Digital I/O Object % add the hardware lines 0 until 7 from port 0 to the addline(dio,0:7,0,'out'); %Send data to the lines for i=1:20 putvalue(dio.line(1),1); % send data ‘1’ to line 1 pause(1) putvalue(dio.line(1),0); % send data ‘1’ to line 1 end
101
Parallel Port % Create a Digital I/O Object with the digitalio function dio=digitalio('parallel',‘lpt1'); % LPT 3 Port 0,1,2 %Add lines to a Digital I/O Object % add the hardware lines 0 until 7 from port 0 to the addline(dio,0:7,0,'out'); %Send data to the lines for i=1:20 putvalue(dio.line(1:8),[ ]); pause(1) putvalue(dio.line(1:8),[ ]); end
102
Sound Card Example: Record and play back 5 seconds of 16-bit audio
sampled at kHz Fs = 11025; y = wavrecord(5*Fs, Fs, 1); wavplay(y, Fs); Example: Read and play sampled at kHz Fs = 11025; y = wavread(‘d:\moh\sound.wav'); wavplay(y, Fs);
103
Camera and Image % Initiate the camera
vid = videoinput('winvideo', 1); set(vid, 'ReturnedColorSpace', 'RGB'); img = getsnapshot(vid); imshow(img) imwrite(img,'d:\1\ball24.jpg'); photo=img; photo=imread('d:\1\ball7.jpg'); figure image(photo)
104
Image processing in matlab
To read and display images im = imread(“filename.fmt”) im is r x c if gray scale im is r x c x 3 if color image (RGB) imshow(im) % displays image imwrite(im, “filename.fmt”) % writes image Size of image [r c] = size(im) Examples during Matlab demo
105
DSP Common Signal FFT
106
FFT clear all; for i=1:10000 t=0.01*(i-1) x(i) = 5*sin(3*2*pi*t); end
plot(x(i)) axis([ ]) grid figure y = fft(x,10000); my = abs(y)/10000; plot(my); axis([ ])
107
Non-periodic Signals Step Impulse Ramp Nonperiodic Signals
>> t = linspace(0,1,11); Step >> y = ones(11,1); Impulse >> y = [1;zeros(10,1)]; Ramp >> y = 2*t; Useful MATLAB functions step, impulse, gensig Non-periodic Signals >> t = linspace(0,1,11) Step >> y = ones(11,1); Impulse >> y = [1;zeros(10,1)]; Ramp >> y = 2*t; Try Step function: >> fs = 10; >> ts = ... [0:1/fs:5, :1/fs:10]; >> x = [zeros(1,51), ... ones(1,51)]; >> stairs(ts,x) Impulse function with width w: >> w = 0.1; [-1:1/fs:-w, ,w:1/fs:1]; >> x = [zeros(1,10), ... 1,zeros(1,10)]; >> plot(ts,x) Delta function impulse: >> ts = 0:0.5:5; >> x = [1, zeros(1, length(ts)-1)]; >> stem(ts,x) >> axis([ ]) Step Impulse Ramp
108
Sine Waves Parameters Amplitude A Frequency f Phase shift φ
Sine wave parameters Amplitude A Frequency f Phase shift φ Vertical offset B The general form of a sine wave is Example: Generate a sine wave given the following specifications: A = 5 f = 2 Hz φ = π/8 >> t = linspace(0,1,1001); >> A = 5; % Amplitude >> f = 2; % Frequency in Hertz >> p = pi/8; % Phase in radians >> sinewave = A*sin(2*pi*f*t + p); >> plot(t,sinewave) Sine Waves Parameters Amplitude A Frequency f Phase shift φ Vertical offset B General form Try >> edit sine_wave >> sine_wave >> edit sinfun >> [A,T] = ... sinfun(1,2,3,4) Exercise High and Low (p. AIII-3)
109
Square Waves Duty cycle is 50% (default) Frequency is 4 Hz
Square wave generation is like sine wave generation, but you specify a duty cycle, which is the percent of time over one period that the amplitude is 1. Example: Duty cycle is 50% (default) Frequency is 4 Hz >> t = linspace(0,1,1001); >> sqw1 = square(2*pi*4*t); >> plot(t,sqw1) >> axis([ – ]) Duty cycle is 75% >> sqw2 = square(2*pi*4*t,75); >> plot(t,sqw2) Square Waves >> sqw1 = square(2*pi*4*t); Duty cycle is 50% (default) Frequency is 4 Hz Try >> t = ... linspace(0,1,1001); >> sqw1 = ... square(2*pi*4*t); >> plot(t,sqw1) >> axis(... [ – ]) >> sqw2 = ... square(2*pi*4*t,75); >> plot(t,sqw2) >> sqw2 = square(2*pi*4*t,75); Duty cycle is 75% Frequency is 4 Hz
110
Sawtooth Waves Peak at end of cycle (default) Frequency is 3 Hz
Sawtooth waves are like square waves except that instead of specifying a duty cycle you specify the location of the peak. Example: Peak at end of cycle (default) Frequency is 3 Hz >> t = linspace(0,1,1001); >> saw1 = sawtooth(2*pi*3*t); >> plot(t,saw1) Peak halfway through cycle >> saw2 = sawtooth(2*pi*3*t,1/2); >> plot(t,saw2) Sawtooth Waves >> saw1 = sawtooth(2*pi*3*t); Peak at end of cycle (default) Frequency is 3 Hz Try >> t = ... linspace(0,1,1001); >> saw1 = ... sawtooth(2*pi*3*t); >> plot(t,saw1) >> saw2 = ... sawtooth(... 2*pi*3*t,1/2); >> plot(t,saw2) >> saw2 = sawtooth(2*pi*3*t,1/2); Peak halfway through cycle Frequency is 3 Hz
111
FFT clear all; for i=1:10000 t=0.01*(i-1) x(i) = 5*sin(3*2*pi*t); end
plot(x(i)) axis([ ]) grid figure y = fft(x,10000); my = abs(y)/10000; plot(my); axis([ ])
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.