MATLAB Introduction Main Features Simple programming rules Extended accuracy Continuity among integer, real and complex values Comprehensive mathematical library Extensive graphics tools Linkages with other languages Transportability across environment MATLAB scripts will work on PC, UNIX, Mac 1
Typical uses include: Math and computation Algorithm development Modelling, simulation and prototyping Data analysis, exploration and visualization Scientific and engineering graphics Application development, including Graphical User Interface (GUI) building
The Advantages of MATLAB Ease of Use. Platform Independence Predefined Function. Device-Independent Plotting. Graphical User Interface. MATLAB Compiler. a fraction of the time it would take to write a program in a scalar non-interactive language such as C, C++ or Fortran. MATLAB is the tool of choice for high-productivity research, development and analysis
Disadvantage it is an interpreted language and therefore can execute more slowly than compiled languages. a full copy of MATLAB is five to ten times more expensive than a conventional C or Fortran compiler.
Starting MATLAB On UNIX : type matlab at command prompt Click on the MATLAB icon if you are on a PC Mac can probably do both… Issues on startup MATLAB needs a connection to the license server Check internet connection Too many users can use all available licenses 5
Starting MATLAB Once MATLAB is running the GUI (Graphical User Interface) will appear Default Window apperance 6
Starting MATLAB Command Window Main window in MATLAB Commands entered here 7
Starting MATLAB MATLAB displays >> prompt when ready for a command Will have no >> prompt when processing commands Newer versions also say “Ready” or “Busy” in lower left corner of GUI Can use arrow keys to work through command history and modify commands Essentially the same as UNIX command prompt 9
“MATrix LABoratory” Powerful, extensible, highly integrated computation, programming, visualization, and simulation package Widely used in engineering, mathematics, and science Why? Interactive code development proceeds incrementally; excellent development and rapid prototyping environment
Basic data element is the auto-indexed array This allows quick solutions to problems that can be formulated in vector or matrix form Powerful GUI tools Large collection of toolboxes: collections of topic-related MATLAB functions that extend the core functionality significantly
Signal & Image Processing MATLAB Toolboxes Signal & Image Processing Signal Processing Image Processing Communications Frequency Domain System Identification Higher-Order Spectral Analysis System Identification Wavelet Filter Design Control Design Control System Fuzzy Logic Robust Control μ-Analysis and Synthesis Model Predictive Control Math and Analysis Optimization Requirements Management Interface Statistics Neural Network Symbolic/Extended Math Partial Differential Equations PLS Toolbox Mapping Spline Data Acquisition and Import Data Acquisition Instrument Control Excel Link Portable Graph Object Intro MATLAB 12
Toolboxes, Software, & Links Intro MATLAB 13
MATLAB System Language: arrays and matrices, control flow, I/O, data structures, user- defined functions and scripts Working Environment: editing, variable management, importing and exporting data, debugging, profiling Graphics system: 2D and 3D data visualization, animation and custom GUI development Mathematical Functions: basic (sum, sin,…) to advanced (fft, inv, Bessel functions, …) API: can use MATLAB with C, Fortran, and Java, in either direction
Desktop Tools (Matlab v6) Command Window type commands Workspace view program variables clear to clear double click on a variable to see it in the Array Editor Command History view past commands save a whole session using diary Launch Pad access tools, demos and documentation
Data Types logical char CELL structure Java Classes Function handle ARRAY NUMERIC ------------------------int,single,double
Variable Basics >> 16 + 24 ans = 40 >> product = 16 * 23.24 product = 371.84 >> product = 16 *555.24; >> product 8883.8 no declarations needed mixed data types semi-colon suppresses output of the calculation’s result Intro MATLAB 17
Variable Basics >> clear clear removes all variables; >> product = 2 * 3^3; >> comp_sum = (2 + 3i) + (2 - 3i); >> show_i = i^2; >> save three_things >> load three_things >> who Your variables are: comp_sum product show_i >> product product = 54 >> show_i show_i = -1 clear removes all variables; clear x y removes only x and y complex numbers (i or j) require no special handling save/load are used to retain/restore workspace variables use home to clear screen and put cursor at the top of the screen Intro MATLAB 18
The basic data type used in MATLAB is the double precision array MATLAB Data The basic data type used in MATLAB is the double precision array No declarations needed: MATLAB automatically allocates required memory Resize arrays dynamically To reuse a variable name, simply use it in the left hand side of an assignment statement MATLAB displays results in scientific notation Use File/Preferences and/or format function to change default short (5 digits), long (16 digits) format short g; format compact (my preference) Intro MATLAB 19
Matrices a vector x = [1 2 5 1] x = 1 2 5 1 1 2 5 1 a matrix x = [1 2 3; 5 1 4; 3 2 -1] 1 2 3 5 1 4 3 2 -1 transpose y = x.’ y = 1 2 5
Matrices x(i,j) subscription whole row whole column y=x(2,3) y = 4 3 2 -1 y=x(:,2) 2 1 x(i,j) subscription whole row whole column
Operators (arithmetic) + addition Subtraction Multiplication / division ^ power ‘ complex conjugate transpose .* element-by-element mult ./ element-by-element div .^ element-by-element power .‘ transpose
Operators (relational, logical) == equal ~= not equal < less than <= less than or equal greater than >= greater than or equal & AND | OR ~ NOT pi 3.14159265… j imaginary unit, i same as j
Generating Vectors from functions x = zeros(1,3) x = 0 0 0 x = ones(1,3) 1 1 1 x = rand(1,3) 0.9501 0.2311 0.6068 zeros(M,N) MxN matrix of zeros ones(M,N) MxN matrix of ones rand(M,N) MxN matrix of uniformly distributed random numbers on (0,1)
Graph Functions (summary) plot linear plot stem discrete plot grid add grid lines xlabel add X-axis label ylabel add Y-axis label title add graph title subplot divide figure window figure create new figure window pause wait for user response
To create variables >>a=1 a = 1 >> b=4 b = 4 >> c=a+b c = 5 >> d=cos(a) d = 0.5403
>>t=[1 2 3 4 5] t = 1 2 3 4 5 >>t=[1 2 3 4 5]; >> t=1:5 %equally spaced arrays >> t=1:0.5:4 t = 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000
>>Whos %To know the variables typed so far Name Size Bytes Class Attributes a 1x1 8 double b 1x1 8 double c 1x1 8 double d 1x1 8 double t 1x6 48 double
One and two dimentional arrays >>data=rand(2,2) data = 0.8147 0.1270 0.9058 0.9134 >>size(data) ans = 2 2 >>x=3+4i x = 3.0000 + 4.0000i
>>a=[1 2 3;4 5 6;7 8 9] a = 1 2 3 >>b=a' b = 1 4 7 4 5 6 7 8 9 >>a(2,3) ans =6 >>b=a' b = 1 4 7 2 5 8 3 6 9 >>c=a*b c = 14 32 50 32 77 122 50 122 194
>>c=a.*b c = 1 8 21 8 25 48 21 48 81
>> data=rand(5,5) data = 0.5313 0.4235 0.4401 0.9436 0.2891 0.3251 0.0908 0.5271 0.6377 0.6718 0.1056 0.2665 0.4574 0.9577 0.6951 0.6110 0.1537 0.8754 0.2407 0.0680 0.7788 0.2810 0.5181 0.6761 0.2548 >> data(1:3,2:end) ans = 0.4235 0.4401 0.9436 0.2891 0.0908 0.5271 0.6377 0.6718 0.2665 0.4574 0.9577 0.6951 >> data(1:2,:)=0 data = 0 0 0 0 0 0 0 0 0 0
>> a=1.5 a =1.5000 >> whos Name Size Bytes Class Attributes a 1x1 8 double >>format long >>1/7 ans =0.142857142857143 >>format short >> 1/7 ans =0.1429
>>x=3.2 x =3.2000 >>exp(x) ans =24.5325 Boolean Expression >> d(1)=true d =1 >> d(2)=false d = 1 0 >>a=1.5 a = 1.5000 >> a<5 ans = 1
Matrix >>a=[1 2 3 4] a =1 2 3 4 >>a=[1 2;3 4] a = 1 2 3 4 >>a=1:10 a =1 2 3 4 5 6 7 8 9 10
>> a=1:10 a = 1 2 3 4 5 6 7 8 9 10 >> a=1:2:10 a = 1 3 5 7 9 >>10:-2:1 ans =10 8 6 4 2
>>I = eye(3), x = [8; -4; 1], I*x I = 1 0 0 0 1 0 0 0 1 1 0 0 0 1 0 0 0 1 x = 8 -4 1 ans = 4
>> a=rand(4,4) a = 0.8147 0.6324 0.9575 0.9572 0.9058 0.0975 0.9649 0.4854 0.1270 0.2785 0.1576 0.8003 0.9134 0.5469 0.9706 0.1419 >>a(1,2) ans =0.6324
>> a(1,[1,2]) ans = 0.8147 0.6324 >> a(1,:) ans = 0.8147 0.6324 0.9575 0.9572 >> a(1,2:end) ans =0.6324 0.9575 0.9572 a = 0.8147 0.6324 0.9575 0.9572 0.9058 0.0975 0.9649 0.4854 0.1270 0.2785 0.1576 0.8003 0.9134 0.5469 0.9706 0.1419
>> a(1,2:end-1)=[10,10] a = 0.8147 10.0000 10.0000 0.9572 0.9058 0.0975 0.9649 0.4854 0.1270 0.2785 0.1576 0.8003 0.9134 0.5469 0.9706 0.1419 >> a(1:2,:)=[] a = 0.8147 0.6324 0.9575 0.9572 0.9058 0.0975 0.9649 0.4854 0.1270 0.2785 0.1576 0.8003 0.9134 0.5469 0.9706 0.1419
>>a(5) ans = 0.1576 >> a(:) ans = 0.1270 0.9134 0.2785 0.5469 0.1576 0.9706 0.8003 0.1419 a = 0.1270 0.2785 0.1576 0.8003 0.9134 0.5469 0.9706 0.1419
>> a<0.5 ans = 1 1 1 0 0 0 0 1 >> a(a<0.5)= -1 a = -1.0000 -1.0000 -1.0000 0.8003 0.9134 0.5469 0.9706 -1.0000 >> ind=find(a<0.5) ind = 1 3 5 8 a = 0.1270 0.2785 0.1576 0.8003 0.9134 0.5469 0.9706 0.1419
[r,c]=find(a<0.5) r = 1 2 c = 3 4 a= 0.1270 0.2785 0.1576 0.8003 0.9134 0.5469 0.9706 0.1419
>> numel(a) ans = 8 >> a=rand(2,2) a = 0.4218 0.7922 0.9157 0.9595 >> b=[a,a] b = 0.4218 0.7922 0.4218 0.7922 0.9157 0.9595 0.9157 0.9595 0.1270 0.2785 0.1576 0.8003 0.9134 0.5469 0.9706 0.1419
>> b=[a;a] b = 0.4218 0.7922 0.9157 0.9595 >> a=1.5 a =1.5000 >> if a<5 disp('it is within the range') end it is within the range b = 0.4218 0.7922 0.4218 0.7922 0.9157 0.9595 0.9157 0.9595
Character constant >> name='john' name = john >>[name 'smith'] ans =Johnsmith >>name(1:2) ans = jo >> k=1 % index with which to construct a sring k = 1 >> str=['ring' num2str(k)] str = ring1
Structure >> car.year=2010 ans = 2010 >> car.color=‘red’ ans =red >> car.name=‘maruthi’ ans =maruthi
>>car=struct('year','2010','color','red','name','maruthi') >>cars=[car;car] cars = 2x1 struct array with fields: year color name
>> cars(2).name='feat' 2x1 struct array with fields: year color name >>cars.name ans = maruthi ans = feat
>> cars(1).name,cars(2).name ans = maruthi ans = Feat Cell Array mycell={1 2 3;'test' [1;2] false} mycell = [1] [ 2] [3] 'test' [2x1 double] [0]
>> mycell={1, 2,'orange',true} >>y=mycell(1,1) y = [1] >> y=mycell(1,2) [2]
>> y=mycell(1,3) y = 'orange‘ >>y=mycell(1,4) y = [1] >>class(y) ans = Cell
>>y=mycell{1,3} y =orange >>class(y) ans = char
>> mycell{3:4} ans = Orange ans =1 >> newcell={mycell{3:4}} newcell = 'orange' [1]
Flow Control if A > B 'greater' elseif A < B 'less' else 'equal' end for x = 1:10 r(x) = x; if statement switch statement for loops while loops continue statement break statement
>> x = pi*(-1:3), round(x) %Round to nearest integer -3.1416 0 3.1416 6.2832 9.4248 ans = -3 0 3 6 9 >> fix(x) %Round toward zero -3 0 3 6 9 >> floor(x) % rounds against negative infinity -4 0 3 6 9
>> ceil(x) % Round towards positive infinity ans = -3 0 4 7 10 >> sign(x), 1 if the corresponding element of X is greater than zero 0 if the corresponding element of X equals zero -1 if the corresponding element of X is less than zero ans = -1 0 1 1 1
Plotting the figure >>t=0:0.05:0.5 >>y=sin(2*pi*t) y = 0 0.5878 0.9511 0.9511 0.5878 0.0000 >>plot(t,y)
Random Numbers x=rand(100,1); stem(x); hist(x,100)
Line Styles & Colours Colours Line Styles y yellow . point The default is to plot solid lines. A solid white line is produced by >> plot(x,y,'w-') The third argument is a string whose rst character species the colour(optional) and the second the line style. The options for colours and styles are: Colours Line Styles y yellow . point m magenta o circle c cyan x x-mark r red + plus g green - solid b blue * star w white : dotted k black -. dashdot -- dashed
plot(x,y,'*') x=1:5 x = 1 2 3 4 5 >> y=log(x) y = 1 2 3 4 5 >> y=log(x) y = 0 0.6931 1.0986 1.3863 1.6094 >> plot(x,y) plot(x,y,'*')
>>t=[12 23] t =12 23 >> y=[1,5] y =1 5 >> plot(t,y) >> plot(t,y,'r-')
Loops >>x = -1:.05:1; >> for n = 1:2:8 subplot(4,2,n), plot(x,sin(n*pi*x)) subplot(4,2,n+1), plot(x,cos(n*pi*x)) end draw sin(n*pi*x)and cos sin(n*pi*x)for n = 1; 3; 5; 7 alongside each other. We may use any legal variable name as the \loop counter" (n in the above examples) and it can be made to run through all of the values in a given vector (1:8 and 1:2:8 in the examples). We may also use for loops of the type
Matlab Graphics x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x=0:2\pi') ylabel('Sine of x') title('Plot of the Sine Function')
Multiple Graphs t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); plot(t,y1,t,y2) grid on
Multiple Plots t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); subplot(2,2,1) plot(t,y1) subplot(2,2,2) plot(t,y2)
x=1:10; y=1:10; Z=x'*y; surf(x,y,z);
>> [X,Y] = meshgrid(2:.2:4, 1:.2:3); >> Z = (X-3).^2-(Y-2).^2; >> mesh(X,Y,Z) >> title('Saddle'), xlabel('x'),ylabel('y')
>>t=0:0.1:0.5 t =0 0.1000 0.2000 0.3000 0.4000 0.5000 >>y=sin(2*pi*t) y =0 0.5878 0.9511 0.9511 0.5878 0.0000 >>w=y'*y; >>surf(w)
Coin Tosses Simulate the outcomes of 100 fair coin tosses x=rand(100,1); p=sum(x<0.5)/100 p = 0.5400 Simulate the outcomes of 1000 fair coin tosses x=rand(1000,1); p=sum(x<0.5)/1000 0.5110
Coin Tosses Simulate the outcomes of 1000 biased coin tosses with p[Head]=0.4 x=rand(1000,1); p=sum(x<0.4)/1000 p = 0.4160