This action might not be possible to undo. Are you sure you want to continue?

Welcome to Scribd! Start your free trial and access books, documents and more.Find out more

**Matlab programming Fundamentals
**

---------------------------------------------------------------

**Typical uses for Matlab
**

Math and computation Algorithm development Data acquisition Modeling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development, including graphical user interface building

**Matlab programming Fundamentals
**

-----------------------------------------------------------------

What is MATLAB?

MATLAB = MATrix LABoratory MATLAB is a tool for doing numerical computations with matrices and vectors. It is very powerful and easy to use. In fact, it integrates computation, visualization and programming all together in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation and can be used on almost all the platforms: windows, Unix, and Apple Macintosh, etc.

MATLAB is an interactive system whose basic data is a matrix that does not require dimensioning. 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.

**Matlab programming Fundamentals
**

-----------------------------------------------------------------

What is MATLAB?

Its capabilities include:

± ± ± ± ± ± Mathematical computation Graphics and visualization Data analysis Algorithm development Simulation and modeling Programming and application development

³For the purposes of an engineer or scientist, MATLAB has the most features and is the best developed program in its class.´ -IEEE Spectrum, Software Review

More than 65 toolboxes! .Fuzzy Logic . called toolbox . that perform more specialized computations.System Identification Wavelet Filter Design Control Design Control System .Matlab programming Fundamentals -------------------------------------------------------- MATLAB has a number of add-on software modules.Model Predictive Control Model-Based Calibration And More «.Image Processing Communications ..µAnalysis and Synthesis . Signal & Image Processing Signal Processing.Robust Control .LMI Control .

setup Matlab (return) Matlab On both system leave a Matlab session by typing : quit or by typing exit at the Matlab prompt.a double click on the Matlab icon unix system . .Matlab programming Fundamentals ----------------------------------------------------------------- How to start and quit Matlab? PC .

MATLAB Basics On starting MATLAB: * Matlab command window * Matlab Command Prompt .

The following screen will appear when you start up Matlab on windows. All of the commands that will be discussed should be typed at the >> prompt.

Simple computations are very easy. Just type in exactly what you want computed and press enter. If no variables are used, the answer will automatically be assigned to the variable ans.

This variable can be used later, but don't forget that it will automatically be overwritten when a new computation is done.

Variables are also easy to use. Simply type a variable name, the equal sign, and then some value to be assigned.

.At any time. you can type "whos" at the command line to see what variables have been assigned.

. you must first declare a symbolic variable. This is done by typing "syms x" where x is the variable name. x is declared as symbolic and then used to find the indefinite integral and derivative of a function. In the following example.To perform symbolic differentiation or integration.

separated by commas.The definite integral can also be computed by adding the lower and upper bounds. (Note that a function of a valid symbol is still required) . after the function to integrate.

MATLAB Basics Commands The ³help´ command: know which command to use. ± >> help function_name % instructions on named function. ± >> help % lists available packages/toolboxes on system. ± >> help package_name % lists available functions in named package. but need instructions on how to use it. . syntax etc >> help help % instructions on how to get help.

Matlab Help .

General Purpose Commands Helpwin help window with hypertext navigation demo runs MATLAB demos from a MATLAB created Graphic User Interface (GUI) helpdesk troubleshooting with hypertext navigation ver tells you the version of MATLAB being used who lists all variables in the current workspace whos lists all variables in the workspace including array sizes clear clears all variables and functions from memory .

Reserved Words« Matlab has some special (reserved) words that you may not use« for end if while function return elsif case otherwise switch continue else try catch global persistent break .

>> B=123.45 B = 123.Other Points« Typing a ³ . ³ at the end of a statement suppresses echo of the results on the next line Any text following ³ % ³ is ignored (a comment) >> A=100.4500 % important value Type ctrl-c to stop execution of a Matlab Command .2 A = 100.8.2000 >> A=200.

Matlab Editor Access to commands Color keyed text with auto indents tabbed sheets for other files being edited .

perhaps you have not specified a path to find it« .Matlab Path A ³path´ is a string that specifies how to find a resource located in a file system (ex: C:\Matlab_workshop\module_1 ) The Matlab Path is a list of many paths to be searched in succession whenever Matlab needs to find something ± Starts with a basic set of paths ± Can be extended by the user (using File/Set Path«) If Matlab tells you that it cannot locate a file.

int i. i++) { myarray[ i ] = 0. i < 20.0.Note on Indexing of Array Elements Indexing in C/C++ float myarray[20]. for (i = 0. end .0. } Indexing in MATLAB % No declarations % are necessary for i = [1:20] myarray( i ) = 0.

0.2. t(end) Indices start at 1. «] Access individual elements with integer index enclosed in parentheses ( ) >> t(1). 0.1.Manual Definition of t Create with brackets [ ] Separate elements inside with spaces or commas >> t = [0. . t(2).

Checking Workspace Variables are defined in workspace Can list all variables in workspace using the command whos Can clear any or all variables: ± >> clear t ± >> clear all .

´ are simply run with out displaying result lines that do not end with a ³.Simple Examples %Example1. Y=3. Z % character denotes the start of a comment lines that end with a ³.´ are run and results displayed on command window .m X=5. Z=3X^2+5.

.m file it can be run by either pressing F5 in the editor or by typing the file name in the command window Other .m Files Once your program has been saved as a .m files maybe be run from within different .m files .

5 ] . that is. but always beginning with a letter. in which case it is called a row vector of n elements. 33. x = [ 3. 24. 'MID' and 'Mid' are treated as two different variables. or a vector can be represented by a 1 x n matrix. in which case it is called a column vector. x1 = [ 2 5 3 -1]. vector and scalar: A vector of n elements can be represented by a n x 1 matrix. .Matrix.22. Matlab is "case sensitive". x is a row vector or 1 x 3 matrix x1 is column vector or 4 x 1 matrix The matrix name can be any group of letters and numbers up to 19. Similarly.5. it treats the name 'C' and 'c' as two different variables.

8 1.0 .2 .2 : 1. a = [ 1 2 3 4 5 6 7 8 ]. are separated by two colons.0 generates the row vector b = [ 0.0 : . if two integer numbers are separated by a colon.6 .4 . integer or non-integer. For example. the middle number is interpreted to be a ´step" and the first and third are interpreted to be "limits´: b = 0. If three numbers. a = 1:8 generates the row vector.0 ] . Matlab will generate all of the integers between these two integers.Syntax in Matlab: Colon operator: The colon operator ' : ' is understood by Matlab to perform special and useful operations.

Syntax in Matlab: The colon operator can be used to create a vector from a matrix.:) creates the row vector z=[2 6 8] . Thus if x=[2 6 8 0 1 7 -2 5 -6 ] The command y = x(:.1) creates the column vector y=[ 2 0 -2 ] The command z = x(1.

2:3) creates a matrix for which all elements of the rows from the 2nd and third columns are used. If the 4 x 3 matrix c is defined by c = [ -1 0 1 1 1 -1 0 0 Then 0 0 0 2] d1 = c(:. The result is a 4 x 2 matrix d1 = [ 0 1 -1 0 0 0 0 2] .Syntax in Matlab: The colon operator is useful in extracting smaller matrices from larger matrices.

y = sin(x) y=1 .Algebraic operations in Matlab: Scalar Calculations: + addition subtraction * multiplication / right division (a/b means a ÷ b) \ left division (a\b means b ÷ a) ^ exponentiation For example 3*4 executed in 'matlab' gives ans=12 4/5 gives ans=.8 4\5 ans=1.25 x = pi/2.

associative and distributive operations in arithmetic do not always follow.A If C = A + B then each element Cij = Aij + Bij.Algebraic operations in Matlab: Matrix Calculations: Because matrices are made up of a number of elements and not a single number (except for the 1x1 scalar matrix). the ordinary rules of commutative. 5 3 1] B=[2 -3 4. For Example: A and B are defined as follows: A=[1 2 3. 5 7 1] .5 1 5.B = B .2 -2 2. 3 3 3. 0 4 0] Then note that C = A + B and C = B + A gives C =[ 3 -1 7. Addition and Subtraction of Matrices: Only matrices of the SAME ORDER can be added or subtracted. the individual elements are added or subtracted (distributive rule) A+ B = B +A and A . When two matrices of the same order are added or subtracted in matrix algebra.

C. The resulting product. has an order for which the number of rows equals the number of rows of the first (left) matrix (A) and the product (C) has a number of columns equal to the number of columns in the second (right) matrix (B). the elements of the product. It is clear that A*B IS NOT NECESSARILY EQUAL TO B*A! It is also clear that A*B and B*A only exist for square matrices! . In matrix multiplication. matrix C. the number of columns of the first or left matrix (A) must be equal to the number of rows in the second or right matrix (B). of two matrices A*B are calculated from Cij = µ Aik * Bkj To form this sum.Algebraic operations in Matlab: Multiplication of Matrices is more complex than arithmetic multiplication because each matrix contains a number of elements.

6 5]. 3 4]. Calling the product c = a*b c11 = a11*b11 + a12*b21 c12 = a11*b12 + a12*b22 c21 = a21*b11 + a22*b21 c22 = a21*b12 + a22*b22 b = [ 8 7.1)) returns the length of the first column . N] containing the number of rows and columns in the matrix length(a(:.Algebraic operations in Matlab: For Example: two square 2x2 matrices a = [ 1 2. size(a) returns the two-element row vector D = [M.

* b a .Algebraic operations in Matlab: Array products: Recall that addition and subtraction of matrices involved addition or subtraction of the individual elements of the matrices.\ b a .^ b multiplies each element of a by the respective element of b divides each element of a by the respective element of b divides each element of b by the respective element of a raise each element of a by the respective b element .' (period): a ./ b a . Array or element-by-element operations are executed when the operator is preceded by a '. Sometimes it is desired to simply multiply or divide each element of an matrix by the corresponding element of another matrix 'array operations´.

7854 1. Std(A) = Standard deviation column wise of A.6) A=[1:50] A=[0:pi/4:pi]=[0 0.1416] .5) N = randn(6. Mean(A) = Average element column wise of A. Max(A) = maximum element column wise of A.5708 2.Matrix Manipulations Sum(A) = sums of the columns of A A¶ = Transpose of A Diag(A) = gives diagonal elements of A Min(A) = minimum element column wise of A. X = zeros(5.6) M=rand(5.5) Y = ones(6.3562 3.

.) B = magic(4) = [ 16 Dürer's magic square 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1] All numbers are stored internally using the long format specified by the IEEE floating-point standard.Matrix Manipulations (contd. Floating-point numbers have ± finite precision 16 significant decimal digits and ± finite range 10-308 to 10+308. .

2) = [ ] deletes 2nd column. [indices] = find(isprime(A)) format this command can be used for formatting the displayed numeric output (either in short or long format)..) A(:.*5 Element-by-element multiplication.Matrix Manipulations (contd. A(2:2:12) = [ ] results in row vector of remaining elements. . A = A.

A(3.A(2.[1 2]) Ordering of indices is important! >> B=A([3 2].[2 1]) >> B=[A(3.1).2).Indexing Matrices Indexing using parentheses >> A(2.3) Index submatrices using vectors of row and column indices >> A([2 3].1)] .A(2.2).

Indexing Matrices Index complete row or column using the colon operator >> A(1.:) Can also add limit index range >> A(1:2.:) >> A([1 2].:) General notation for colon operator >> v=1:5 >> w=1:2:5 .

<operator>´ is elementwise operation . >> I=eye(3) Elementary functions are often overloaded >> help elmat >> sin(A) Specialized matrix functions and operators >> As=sqrtm(A) >> As^2 >> A. ´.*A Note: in general.Matrix Functions Many elementary matrices predefined >> help elmat.

x=inv(A)*z >> x=A\z Many standard functions predefined >> det(A) >> rank(A) >> eig(A) The number of input/output arguments can often be varied >> [V.3].2.Numerical Linear Algebra Basic numerical linear algebra >> z=[1.D]=eig(A) .

another. MATLAB will also plot a vector vs. dist) >> plot (dist) % plotting versus time % plotting versus index . its own index. The index will be treated as the abscissa vector. Given a vector ³time´ and a vector ³dist´ we could say: >> plot (time.Plotting with MATLAB MATLAB will plot one vector vs. The first one will be treated as the abscissa (or x) vector and the second as the ordinate (or y) vector. The vectors have to be the same length.

we would use: >> title ('Title of my plot') . For example: >> % To put a label on the axes we would use: >> xlabel ('X-axis label') >> ylabel ('Y-axis label') >> % To put a title on the plot. and legends.Plotting with MATLAB There are commands in MATLAB to "annotate" a plot to put on axis labels. titles.

1) . we wish to plot one column vs. If we have a matrix ³mydata´ with two columns. % First column >> second_vector = mydata ( : . Normally.Plotting with MATLAB Vectors may be extracted from matrices. another. 2) . % Second one >> % and we can plot the data: >> plot ( first_vector . we can obtain the columns as a vectors with the assignments as follows: >> first_vector = mydata ( : . second_vector ) .

y) xlabel('X axis description') ylabel('Y axis description') title('Title for plot goes here') legend('Legend for graph') grid on Y ax is des c ription Title for plot goes here 1 Legend for graph 0.05:10*pi.y) but does not have additional options 0 M anually ins erted tex t.*sin(x)..1.y order (y.5 NOTE #1: Reversing the x.. plot(x. y=exp(-.y) pairs defined by symbols or connected with lines >> >> >> >> >> >> >> >> x=0:0.Basic 2D Plotting The simplest kind of plot is a cartesian plot of (x.5 -1 0 5 10 15 20 X ax is des c ription 25 30 35 .x) simply rotates the plot 90 degrees! NOTE #2: line(x.*x). -0.y) is similar to plot(x.

sin(x)) 1 1 >> hold on >> plot(x.5 0 1 2 3 4 5 6 7 -1 0 2 4 6 8 . >> plot(x. >> plot(x.5 .5 >> x=0:0.1:2*pi.5]) 0.cos(x)) 0.1:2*pi.sin(x)) >> axis ans = 0 7 -1 >> axis([0 7 -.5 0 0 -0.5 -0.Supporting Commands Several functions let you control the plot appearance ± axis(): determines the axis scaling (see help for options) ± hold on/off: controls whether or not the plot is erased before another plot is drawn (toggles if no argument given) >> x=0:0.

'b--') 1 x=0:0.6 0.'ro'.cos(x).8 0 0. y=x.4 0. 2 0 0 0.2 0.4 0.*yr.2 0 0.4 -0.2 >> plot(x.2 0.yy.6 0.5 0. yr=randn(size(x)).1.8 1 .Using Lines or Markers or Both« Plots must follow the following logic: ± Lines: whenever plotting analytical functions like sin(x) where you can compute y for any value of x ± Markers: whenever plotting discrete experimental data or whenever the data are known only discretely ± Both: connecting markers with straight lines is appropriate when you want to show a sequence >> >> >> >> >> 1.5.8 1 -0.sin(x).6 0.^1. plot(x.yy.5 1 0. y=x.02:1.*yr.^1. yy=y+0.02:1.4 >> >> >> >> >> x=0:. plot(x.1.'r:') >> hold on >> plot(x. yr=randn(size(x)).2 0 0.2 -1 0 2 4 6 8 -0 .yy) 0.5.6 0.'rx') 1.8 0.x. yy=y+0.2 1 0.

x).6 >> >> >> >> >> >> 15 10 5 0 x=0:0.'ro') hold on plot(x.*y+yr.4 0.*yr.02:1.10.polyval(p. >> yr=randn(size(x)).0159 -0.4 0.yy.Using Both Markers & Lines Use lines to show analytical fit through discrete data >> x=0:.*pi. yr=randn(size(x)). y=sin(x).10. >> plot(x.5.2:2.8 1 -5 -10 -15 0 2 4 6 8 .'r') 1.2 0. plot(x.2 1 0.1.2 0 -0.*y) 0.2 0 0.6 0. >> y=x.^1. >> yy=y+0.1) p = 1.'x') >> p=polyfit(x.yy.8 0.0927 >> hold on >> plot(x.

Y2) plot(X.Y4) 0 -1 -2 -3 0 1 2 3 4 5 6 7 . sin(X).0:pi/100:2*pi. We could plot these using: 3 2 1 >> >> >> >> >> plot(X. cos(2*X). 3*cos(X).Y3) plot(X.Y1) hold on plot(X.Plotting Multiple Curves Problem: How can you compare several curves? Let¶s start with the following: >> X >> Y1 >> Y2 >> Y3 >> Y4 = = = = = 0. cos(X).

X.Plotting Multiple Curves (cont¶d) Or we could do: >> plot(X.Y3.Y3.X.Y1.Y2.X.Y4]. >> plot(X.Y2. How could we see the data points more distinctly? 1 0 -1 -2 -3 0 1 2 3 4 5 6 7 . Z. 'o') 3 2 Do a ³help plot´ for more markers.Y4) 3 2 1 Or we could do this: >> Z = [Y1.Z) 0 -1 -2 -3 0 1 2 3 4 5 6 7 What if we did this? >> plot(X.

y2=90.x.5).5).5 50 0 0 0 -50 -0.*sin(x-0.*pi.y1.*pi.x. y2=90. plot(x. y1=sin(x+0.Using 2 Y-axis Scales Sometimes it is useful to plot two curves with widely different y-axis scales >> >> >> >> 100 x=0:0.1:3.1:3. y1=sin(x+0.5).y1. plotyy(x.y2) 100 50 0.*sin(x-0.5).y2) 1 >> >> >> >> x=0:0.5 -50 -100 0 2 4 6 8 10 -1 0 2 4 6 8 -100 10 NOTE: it is complicated to label the 2nd axis« .

y) ± adds line specified by x & y vectors . xmax. ymin.places horizontal text starting at (x.y) gtext(µstring¶) ± places horizontal text starting wherever user clicks with mouse line(x.freezes current axis scaling axis([xmin.More Plot Commands axis . ymax]) ± sets axis limit values (note use of [ ] ) axis off ± turns off display of axes (plot unchanged) axis on ± turns on display of axes grid on/off ± turns on/off display of a grid text(x.µstring¶) .y.

¶text¶) % adds positioned text Okay. let¶s plot 3 sinusoids using what we know « .ycoord.y) to the screen >> axis([xmin xmax ymin ymax]) % changes axes limits >> xlabel(µtext¶).y) % plots a f(x. So what do we need to know ? >> plot(x.Plotting Simple Graphs First. ylabel(µtext¶) % labels axes >> title(µtext¶) % places a title on plot >> text(xcoord. a quick run through the µbare bones¶ of plotting in Matlab.

-0. % ¶\bf{text}· places text in bold >> text(3. y3 Note :Text must be enclosed in single quotes >> xlabel( ¶\theta (rads)· ).5)').2) >> text(3. in steps of pi/100 >> y1 = sin(x). % \greek places greek characters in >> ylabel( ¶amplitude· ). >> plot(x. >> y2 = sin(x ²0.y3).'sin(x)').y2).0.0)'). % Places text 'sinx' at x.y1). . y2 % overlay again % plots x vs. >> hold on.0.2.y coordinate (3.7.'sin(x-0.'sin(x-1. % Range of 0 < x < 2pi.5).4.0). y1 % This command allows us to overlay plots % plots x vs. >> hold on.0. % y-values of 1st sinusoid %´ ´ ´ 2nd ´ %´ ´ ´ 3rd ´ % plots x vs. >> y3 = sin(x ²1.0.2. >> text(4. >> plot(x. >> plot(x.>> x = 0: pi/10: 2*pi. >> title( ¶\bf{3 Sinusoids}· ).

Quite a nice graph «. Let·s tidy up the axis. add some colour & line styles to distinguish the sinusoids. .

Adjust the axes limits >> axis([0 6 ±1.2 1. Next add colour to distinguish the sinusoids. Defines max/min values of axes. % axis([xmin xmax ymin ymax]). % In this example.2]). . will crop the x-axis and add a little to the y-axis.

Point ^ triangle s square d diamond Color y yellow m magenta c cyan r red g green b blue w white k black So let¶s make. y3 : no line.y. The options are : Linestyle . dotdash Marker + plus sign o circle * aeterisk x cross .The plot function takes extra parameters to allow us to control line properties its most general form is : plot(x. just diamond markers in blue. % The ( _ ) means there shouldn¶t be spaces between the options. . y1 : a solid line with circle markers in black. y2 : a dotdash line with no markers in red.µlinestyle_marker_color¶) % The 3 extra parameters are known as µstyle options¶.solid -.dashed : dotted -.

r'). just diamond markers in blue.'-ok'). x.rµ.'db'). % (y1) a solid line with circle markers in black.'-.'-. >> plot(x. % write 3 plots consecutively in same function . x. Alternatively there is a further extension of plot >> plot(x.y3. % (y2) a dotdash line with no markers in red. % (y3) no line. >> plot(x.y1.'-okµ.y2.The 3 plot functions would become : >> plot(x.y1.y2.y3.'dbµ).

..Finally..Pos) % places the legend in the specified location: 0 = Automatic "best" placement (least conflict with data) 1 = Upper right-hand corner (default) 2 = Upper left-hand corner 3 = Lower left-hand corner 4 = Lower right-hand corner -1 = To the right of the plot . 0). >> legend(µy1¶. % adds text for the corresponding plots legend(µtext1¶. insert a legend.¶y3¶.¶text2¶..¶y2¶.

^2 + (2. damp=0.y) Describes the behavior of vibrating systems 10 1 10 8 10 8 6 4 2 0 10 0 6 4 2 10 -1 10 -2 10 -1 10 0 10 10 -1 1 0 10 0 10 1 0 2 4 6 8 10 .*x).1.^2).y) semilogx(x.05.^2).Example of Log Plots Using a log scale can reveal large dynamic ranges >> >> >> >> >> >> x=linspace(.*damp.y) loglog(x./sqrt((1-x. y=1. plot(x.1000).10.

n=columns in the grid ± k=current focus (numbered row-wise) Let¶s define a 2x3 subplot grid for: subplot(2.n.k) does this« ± m=rows.Subplot Command There are times when it is better to create several smaller plots arranged in some kind of grid. 3 1 2 4 5 6 2 3 .1) with the focus on the first plot. subplot(m.3.

ylabel(µy¶). subplot(2. .2. semilogx(X.Y). . . title(µPolynomial ± Linear/Log¶).2...1).On Your Own: Putting it all together« X=0:0. title(µPolynomial ± Log/Log¶). grid What does grid do? What¶s the quickest way to execute this code? . loglog(X.Y)..^2. plot(X.Y). ylabel(µy¶).Y). title(µPolynomial ± Linear/Linear¶). semilogy(X. grid subplot(2. grid subplot(2. title(µPolynomial ± Log/Linear¶). Y=5*x..3).2.2.. ylabel(µy¶)..5:50. .2)...4). grid subplot(2. ylabel(µy¶).

z] = simulate(n). Tells MATLAB this is a function List of output values returned (can be any form of array data type) Name of the function List of input argument values.Example of a MATLAB function function [meanr. comma delimited (any form of array data type) . stdr.

m Use Matlab Editor .Create circle1.

CIRC = 2.R) fprintf('\n Area = %f units squared'.0 * pi * R. R = input('Please enter the radius: µ. AREA = pi * R^2. Error in ==> C:\MATLAB6p1\work\circlex. . CIRC) ??? Undefined function or variable 'x'.x).x). fprintf('\n Radius = %f units'.m On line 5 ==> R = input('Please enter the radius: '. AREA) >> circlex fprintf('\n Circumference = %f units\n'. % allowing the radius as an input.When Your Program Detects an Error« Most programs don¶t work right the first time« % This program will calculate the % area and circumference of a circle.

566371 units squared Circumference = 12.R) fprintf('\n Area = %f units squared'.566371 units >> . AREA) >> circlex fprintf('\n Circumference = %f units\n'. % allowing the radius as an input.0 * pi * R. CIRC) Please enter the radius: 2 Radius = %f units Area = 12. fprintf('\n Radius = %%f units'.Sometimes It Looks Like the Program Works« Be careful not to consider any output as good! % This program will calculate the % area and circumference of a circle. CIRC = 2. R = input('Please enter the radius: µ.x). AREA = pi * R^2.

4159 .10) ans = 31.Matlab Functions (m-functions) M-functions are like ³functions´ in algebra ± Algebra: function is a rule that assigns a value based on specified values of the function arguments ± Matlab: function is a program module that computes a returned variable based on specified values of the function arguments >> cylinder(1.

*length.M-function Structure Function definition Returned variable function volume=cylinder(radius. length) % volume=pi.*radius^2. Arguments Help comments Statements (no end required) NOTE: function names are NOT case sensitive in Windows . length) % CYLINDER computes volume of circular cylinder % given radius and length % Use: % vol=cylinder(radius.

View & Text menus do« . Edit. make sure file name is same as function name (the file name is what Matlab uses to identify your m-functions) On Your Own: Figure out what all the options in the File.Using M-File Editor to Create a Function From Command menu choose File/New/M-file ± new edit window will appear with "Untitled" ± enter code for your new function ± when saving.

volume]=cylinderAV(1.10) area = 69.M-functions Can Return Multiple Values The returned variable from an M-function can be a scalar or an array (even a cell array) M-functions can use the [ ] constructor to return an array formed from multiple scalar values >> [area.1150 volume = 31.10) result = 69.1150 >> whos Name Size ans 1x1 area 1x1 result 1x1 volume 1x1 Note that using only a single returned variable receives only the first of multiple values Bytes Class 8 double array 8 double array 8 double array 8 double array .4159 >> result=cylinderAV(1.

SLOW! M-functions are compiled into ³p-code´ the first time they are invoked and this p-code is then executed ± This is MUCH faster than command interpretation ± Editing an M-function will discard the old p-code ± Repeated function executions are much faster this way! You can force-compile an M-function into p-code and save the pcode in a ³p-file´ ± pcode myfunction creates myfunction.M-functions are the Core of Matlab Matlab scripts must be processed line by line by the command processor: TIME CONSUMING.p ± The p-code can be distributed just like an M-function ± Users cannot easily decode your function Learn to make use of M-functions! .

% TIC simply stores CLOCK in a global variable. Inc. % Copyright 1984-2000 The MathWorks.TICTOC).8 $ $Date: 2000/06/01 16:09:45 $ % time (in seconds) since TIC was used. % The sequence of commands % TIC. % Copyright 1984-2000 The MathWorks.TICTOC) else t = etime(clock. % TOC. end if nargout < 1 elapsed_time = etime(clock. prints the elapsed % $Revision: 5. saves the elapsed time in t. CLOCK.Example M-function function tic %TIC Start a stopwatch timer. CPUTIME. Inc. CPUTIME. TOC % prints the number of seconds required for the operation.'). end .9 $ $Date: 2000/06/01 16:09:47 $ % TOC uses ETIME and the value of CLOCK % saved by TIC. operation. % function t = toc % See also TOC. ETIME. % $Revision: 5. by itself. global TICTOC % TICTOC = clock. % t = TOC. CLOCK. % instead of printing it out. global TICTOC if isempty(TICTOC) error('You must call TIC before calling TOC. % See also TIC. ETIME. %TOC Read the stopwatch timer.

1*t).1:30.Continuous-Time Signals x (t ) ! e 0.*sin(2/3*t). x=exp(-.x) grid xlabel('x(t)') ylabel('Time (sec)') . plot(t.1 t 2 sin t 3 % M-File t=0:0.

5 y[n 1] sin(Tn / 4) u[ n] % M-File n=0:20. p(1)=0 . 5 end stem(n. xlabel('n').5 y(t)=0. for t=2:20 y [n] 1 y(0)= 0 1. 3 3 (c ) 0. 0 -0 .5 P lo t o f a D is c re t e s ig n a l 1 .p) grid.33 (c)') -1 -1 . y(1)=sin(pi/4). 5 0 2 4 6 8 10 n 12 14 16 18 20 . p(2)=y(1).Example of discrete-time signal y[ n] for 0 e n e 20 y[ n] ! 0. title(' Plot of a Discrete signal 1.ylabel('y[n]'). p(t+1)=y(t).5*y(t-1) +sin(pi*t/4).

q=size(t).7b Signal g(t) multiplied by a pulse functions').01:5. f=zeros(q(1). plot(t.1. axis([-2. .5.4]).5-cos(5*t(101:501) by a pulse functions ([u(t+1)-u(t-3)] % Signal g(t) multiplied by a pulse functions t= -2:0.-1.f).% Signal g(t) multiplied f(101:501)=2. t'). f(101:501)=2.title('Fig. xlabel('time. grid. ylabel(' g(t)[u(t+1)-u(t-3)]').q(2)).5-cos(5*t(101:501)).

% Signal g(t) multiplied by a pulse functions .

f=2*(n-10). stem(n. g ( n) ! B (n n0 ) MATLAB Code: n=-10:1:20.Sequences Ramp Sequence A shifted ramp sequence with slop of B is defined by: The unit ramp sequence and shifted ramp sequences Example: g(t) = 2(n-10). .f).

Real Exponential Sequences f ( n) ! A( a ) n Real exponential sequence is defined as: Example for A = 10 and a = 0. as n goes to infinity the sequence approaches zero and as n goes to minus infinity the sequence approaches plus infinity. Composite sequence: p ( n ) ! ( a ) n u ( n) Multiplying point by Point by the step sequence MATLAB Code: n=-10:1:10.f). axis([-10 10 0 30]).9.9). f =10*(. . stem(n.^n.

f).Sinusoidal Sequence A sinusoidal sequence may be described as: ¨ 2Tn ¸ f ( n) ! A cos© E ¹ ª N º Where A is positive real number (amplitude). N = 16 And a ! T / 4. stem(n. and a is the phase. f=5*[cos(n*pi/8+pi/4)]. . MATLAB Code: n=-20:1:20. Example: A = 5. N is the period.

^n].9 . MATLAB Code: n=-20:1:20. f=10*[0. h=f .Exponentially Modulated Sinusoidal Sequence By multiplying an exponential sequence by sinusoidal sequence. . N = 16.h). g=[cos(2*n*pi/16+pi/4)].9 E ! T / 4. we obtain an exponentially modulated sequence described by: ¨ 2Tn ¸ g (n) ! (a ) n cos© E ¹ ª N º Example: A = 10. stem(n. axis([-20 20 -30 70]). a = 0.*g.

htm A course on Matlab from UofA ± http://www.Jon.Vis.mathworks.mathworks.ca/CNS/RESEARCH/Courses/2003/MathPackages/Matlab/M atlab.shtml Matlab tutorial.html A Practical Introduction to Matlab ± http://www. with lots of links to other tutorials ± http://www.REFERENCES Matlab homepage (news & more): http://www.html A quick reference to some of the key features of Matlab ± http://science.html Matlab graphics ± http://www.ualberta.math.com/ Getting started with Matlab ± http://www.umd.ntu.com/access/helpdesk/help/techdoc/learn_matlab/learn_m atlab.index.ca/~appinst/doc/matlabhelp/techdoc/umg/chintro.uk/msor/ccb/matlab.edu/~nsw/ench250/matlab.mtu.html#MATLAB .glue.edu/~msgocken/intro/intro.ac.ucalgary.

- A Fast Method for Applying Rigid Transformations to Volume Data
- Introduction to Matlab 1
- 044.01 Shanti an Indexing Method for Handling Queries on Setvalued Attributes in ODBMS March 2008
- 9410965
- Fundamentals of PLC Final
- Information Theory Inference and Learning Algorithms - David Mackay
- kalibond
- jgt98convex Convex Coding
- Matlab 1
- UPF_ Chapter 3_ Subroutines for Users' Convenience (UP19980820)
- Scilab Tutorials for Computational Science
- refcard-a4.
- 0
- matlab
- Solving Fredholm Integral Equations of the Second Kind in MATLAB
- Matlab
- cs377s-Jan17_2
- ese576
- Byzentine Clocks
- Duration Types
- Comparative Analysis of Various Wavelet Filters for Compression of an Image
- Soft Computing Techniques for the Control of an Active Power Filter(PI algorithm,Fuzzy Control Scheme For APF, Neuro-Fuzzy Control Scheme for APF,Fuzzy-Genetic Control Scheme for APF)
- EnodeLDPCPubDat_166941
- Paperiros Srt h
- Mat Labs i Mu Link Tutorial
- ACADO for Matlab User's Manual
- Mining of Massive Datasets
- BAB01- Introduction to Simulink
- PSAT
- Question Bank

Are you sure?

This action might not be possible to undo. Are you sure you want to continue?

We've moved you to where you read on your other device.

Get the full title to continue

Get the full title to continue listening from where you left off, or restart the preview.

scribd