Chapter 1 Introduction to MATLAB 1.1 What is MATLAB? MATLAB = MATrix LABoratory, the language of technical computing, modeling and simulation, data analysis and processing, visualization and graphics, and algorithm development. 1.2 MATLAB System The MATLAB system consists of five main parts: 1. Development Environment: set of tools and facilities that help you use MATLAB functions and files. Many of these tools are graphical user interfaces. It includes the MATLAB Command Window, Launch Pad Window, Workspace Window, Command History 1
, Current Directory Window, Editor and Debugger, Help Window, and Figure Window. 2. The MALAB Mathematical Function Library: a vast collection of computational algorithms. 3. The MATLAB Language: This is a high-level matrix/array language with control flow statements, functions, data structures, input/output, and objected-oriented programming features. 4. Graphics: MATLAB has extensive facilities 2-D and 3-D data visualization, animation, and presentation graphics. 5. The MATLAB Application Program Interface (API): allows you to write C and Fortran programs that interact with MATLAB. 1.3 Programming Mode 1.3.1 Use Command Window The Command Window is MATLAB s main window and opens when MATLAB is started. 2
For simple and short calculation, you only need to type your functions (or command) and variables and the MATLAB prompt in the command window, and hit enter key to run and show your result. Note: 1) Calculation result is displayed in Command Window, graphical result by graphics commands will be displayed in an automatically opened Figure Window. 2) A semicolon (;) typed in the of a command can hide its corresponding result. 1.3.2 Use Editor/Debugger Window The Editor Window is used for writing and editing programs. For complex task that includes many calculations and commands, you d better write your commands into a script file (its type is filename.m and can be saved and opened at any time) using editor, and debug it. It is also called M-file. 3
You can run the file by two ways: 1). Without open the script file in the Editor Window, run it at the MATLAB prompt in the Command Window by typing your.m filename and hit enter key, e.g. >> filename The calculation results will be displayed in the command window as well. 2). If the script file is open in the Editor Window, you can run it by clicking the Run icon on the toolbar. 1.4 Language Basic 1.4.1 Basic Arithmetic Operators Operation Symbol Example Addition + Subtraction - Multiplication * Right division / Left division \ Exponential ^ Assign = Note: MATLAB is case sensitive. i.e. Variables a and A are not same. Built-in variables: 1). i or j ----------aqrt(-1) 2). pi -------------3.1415926535897932 3). Inf ------------ or 1/0 4). NaN ----------not a number (0/0) 4
1.4.2 Basic Built-in Math Functions Command Description Example sqrt(x) Square root exp(x) Exponential abs(x) Absolute value log(x) Natural logarithm ln(x) Base e logarithm log10(x) Base 10 logarithm sin(x) Sine of angle x (x in radians) asin(x) Inverse sine of x (result in radians) round(x) Round to nearest integer ceil(x) Round up toward infinity floor(x) Round down toward minus infinity 1.4.3 Number Display Format Command Description Example format short Fixed point with >>format short; 290/7 four decimal digits for: 0.001 number 1000 format long Fixed point with 15 >>format long; 290/7 decimal digits for: 0.001 number 1000 format short e Scientific notation >>format short e; 290/7 with four decimal digits format long e Scientific notation with 15 decimal digits >>format long e; 290/7 To display variable name and its value, use fprintf(`my variable %5.2f more text, variablename) 5
1.4.4 Array In MATLAB, all variables are dealt as array, and matrix is a rectangular array of numbers. scalar = 1-by-1 matrix vector = one row or column matrices 1.4.4.1 Creating Array 1). Row vector: 2). Column vector: 3). Matrix: 4). Row vector with constant spacing can be created by two ways: a). colon operator (:): Unit spacing: Non-unit spacing b). built-in function linspace(startvalue, Value, spacenumber): Example 1.1 Create a vector consisting of 6 numbers from 0 to 8 with equal spacing. 6
1.4.4.2 Array Addressing To locate a single element in an array, you need to point out its row and column positions. The element in row i and column j of array A is denoted by A(i, j). Example 1.2 To create a submatrix from a matrix A, Example 1.3 To combine two matrix to create a new matrix by juxtaposition, Example 1.4 1.4.4.3 Array Operation 1). Operation by algebra rules The array addition, subtraction and multiplication operation following the rules of linear algebra can only be undertaken on arrays of identical size. 7
Array division is not defined in linear algebra, instead it can looked as multiply with the inverse of the matrix of interest. 2). Element-by-element operation The algebra array addition, subtraction are element-by-element operation already. However, multiplication, division and exponential operations are different. Symbol Description.* Multiplication./ Right division.\ Left division.^ Exponentiation Example 1.5 Given array A and B as below, use MATLAB to compare A*B and A.*B. Other built-in functions for handing arrays can be seen below. Command Description Example length(a) Returns the number of elements in vector A size(a) Returns a row vector [m,n], where m is the number of rows, and n the number of columns in A zeros(m,n) Create a matrix with m rows and n columns 0s. ones(m,n) Create a matrix with m rows and n columns 1s. 8
mean(a) sum(a) det(a) For vector A, mean(a) returns the mean value of the elements in A. For matrix A, mean(a) returns a row vector containing the mean value of each column. For vector A, sum(a) returns the sum of the elements in A. For matrix A, sum(a) returns a row vector containing the sum of each column. Returns the determinant of a square matrix A 1.4.5 Program Flow Control 1.4.5.1 Relational and Logical Operators Relational Operator Description Relational Operator < >= > = = <= ~= Description Logical operator Name Description & AND A&B, if both A and B are true, the result is true (1); otherwise, the result is false (0). OR A B, if either one or both A and B are true, the result is true (1); otherwise (both are false) the result is false (0). ~ NOT ~A, gives the opposite of A. 1.4.5.2 if-else- Conditional Control It is similar to if-else statement in C++, but for each if-else pair you need to add one to denote the of the control. if condition group commands 1 else group commands 2 9
or if condition 1 group commands 1 else if condition 2 group commands 2 else group commands 3 Example 1.6 if x >= y c = x ^ 2 - y; else if y / x > 2.0 c = log(y / x); else c = x + y; 1.4.5.3 for- Loop It is similar to for statement in C++, but for each for you need to add one to denote the of the loop. for i = startvalue:step:value group commands Example 1.7 Calculate the sum of 5 to 10. 1.4.5.4 while- Loop It is similar to while statement in C++, but for each while you need to add one to denote the of the loop. while condition group commands 10
1.4.5.5 switch-case- Control It is similar to switch-case statement in C++, but for each switch-case you need to add one to denote the of the control. switch expression case value 1 group commands 1 case value 2 group commands 2 case value 3 group commands 3 Otherwise group commands n 1.4.6 Plotting Display your graphic result, you need use plotting. MATLAB has a lot of built-in plotting function, the simplest one is: plot(x,y) where X and Y are vectors of same size. This function creates a two-dimensional plot in the Figure Window to show a single curve with the x values on the horizontal axis and y values on the vertical axis. Example 1.8 In the Command Window, draw the curve connecting points (1, 2), (2, 6.5), (5, 7), (7, 12), (10, 8). 11
12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 If you want to plot multiple curves in the same Figure Window, use plot(x, Y1, X, Y2, X,Y3) You can also change the default line type (solid) and color (blue) for the curve. Add a line specification in the plot function as below plot(x,y1, `r:, X, Y2, `g-, X, Y3, `y-. ) You can also add text label for horizontal and vertical axis and tiltle in the plot, just add xlabel(`text string for x-axis ) ylabel(`text string for y-axis ) titlel(`description of the plot ) To learn more details about plot(), just type help plot in the Command Window and enter, it will display the explanation for the function. For any other function information, you can use similar way in Command Window >>help functionname 1.5 Script File 1.5.1 Create and Save Script files are created and edited in the Editor/Debugger Window which can be opened by selecting menu: 1). File>New>Blank M-file 12
This opens the window with an empty page for writing new program. You can save the script file at any time before closing the editor window by selecting menu on the Editor Window: File>Save as 2). File>Open If a M-file already exists, you want to open it and modify. This opens the window listing files for selecting, find the M-file you are interested and open it, then the file display in the Editor Window. 1.6 Function File You can make your own function by writing commands and saved them as a function file. The function file can be called in another script file like MATLAB built-in function. Function file is created and edited regular script files. To create a new one, just select menu: File>New>Function M-file This opens the window with formatted page for writing new function program as below: function [ output_args ] = Untitled1( input_args ) %UNTITLED1 Summary of this function goes here % Detailed explanation goes here 13
You can change the default function name Untitled1 to what you want, and rename the default output argument output_args and input argument input_args or add more arguments. Write your other implementation commands above the given. When you finish coding, you can save it as script file. Note: The function file name should be the same as the function name. Example 1.9 Write MATLAB code to calculate the mean of elements in a row vector X consisting of 0, 1, 2, 3,,99. Above is the function file calculateaverage.m, to use it (for example, in Command Window): 14