MATLAB is the main panel where you interact with MATLAB. You key (or type) and commands after the prompt >>; MATLAB executes the commands and displays results (if requested) Some commonly used tools and commands: - (up arrow) returns last command input, can be repeated - (clc) clears the screen - whos - shows list of variables - clear - clears variables Throughout the lecture, yellow text indicates what you should type into MATLAB.
MATLAB is the main panel where you interact with MATLAB. You key (or type) and commands after the prompt >>; MATLAB executes the commands and displays results (if requested) Some commonly used tools and commands: - (up arrow) returns last command input, can be repeated - (clc) clears the screen - whos - shows list of variables - clear - clears variables Throughout the lecture, yellow text indicates what you should type into MATLAB.
MATLAB is the main panel where you interact with MATLAB. You key (or type) and commands after the prompt >>; MATLAB executes the commands and displays results (if requested) Some commonly used tools and commands: - (up arrow) returns last command input, can be repeated - (clc) clears the screen - whos - shows list of variables - clear - clears variables Throughout the lecture, yellow text indicates what you should type into MATLAB.
MATLAB is the main panel where you interact with MATLAB. You key (or type) and commands after the prompt >>; MATLAB executes the commands and displays results (if requested) Some commonly used tools and commands: - (up arrow) returns last command input, can be repeated - (clc) clears the screen - whos - shows list of variables - clear - clears variables Throughout the lecture, yellow text indicates what you should type into MATLAB.
Essential MATLAB for Engineers and Scientists By Hahn & Valentine 2007 Daniel Valentine. All rights reserved. Published by Elsevier. http://www.mediafire.com/?y5dz4zjxrj0z4 Email: bttu@fetel.hcmus.edu.vn 1 MATLAB desktop Command Window
Command History Window
Workspace Window
Current Directory Window
Start Button 2 Command Window The Command Window on the right is the main panel where you interact with MATLAB. You key (or type) and <Enter> commands after the prompt >>; MATLAB executes the commands and displays results (if requested). Some commonly used tools and commands: (up arrow) returns last command input, can be repeated clc clears the screen whos shows list of variables clear clears variables 3 Evaluation of MATLAB HANDS-ON with MATLAB Type >> 2+3 <Enter> into the Command Window >> clc <Enter> >> whos <Enter> Throughout the lecture, yellow text indicates what you should type into MATLAB. 4 Command History Window The Command History Window logs all of the commands you enter in MATLAB. It should have logged 2+3. Use the Command History Window to reenter 2+3 in the command window (use copy-and- paste or double click on 2+3). This is useful to retrieve past commands. Use Shift key to select multiple lines. 5 Arithmetic with MATLAB Let us explore by doing exercises:
>> 32 <Enter> >> 3*2 <Enter> >> 3/2 <Enter> >> 3\2 <Enter> >> 3^2 <Enter> >> 2/0 <Enter> >> 0/2 <Enter> >> 3*Inf <Enter> 6 Algebraic-numeric computations Let us explore by doing exercises: >> a = 3 <Enter> >> b = 2 <Enter> >> a b <Enter> >> a / b <Enter> >> a^2 <Enter> >> c = a * b <Enter> >> d = c^(b+1) <Enter> >> who 7 Hiding Output Let us explore by doing exercises: >> clear; clc <Enter> >> whos <Enter> >> a = 3; <Enter> >> b = 2; <Enter> >> c = a * b; <Enter> >> d = c^(b+1); <Enter> >> who <Enter> >> % a, b, c, d are in workspace<Enter> >> a, b, c, d <Enter> 8 Plot y versus x Introduction to plotting & displaying data: >> clear; clc <Enter> >> x = 0:0.1:1; <Enter> >> y = x.^2; <Enter> >> whos <Enter> >> plot(x,y,x,y,o) <Enter> >> disp(' '),disp('...... x ........ y .....'),disp([x y']) <Enter> >> x <Enter> >> y <Enter> >> % x and y are 1-by-11 arrays of numbers! 9 Write a Simple Program Consider computing the volume of a cone: Volume = (pi.*r.^2.*h)./3 radius = 6 inches height = 12 inches
In the command window key in: >> clear; clc <Enter> >> r = 6 <Enter> >> h = 12 <Enter> >> v = (pi.*r.^2.*h)./3 <Enter> >> whos <Enter> 10 Editor & M-Files An M-file in MATLAB is analogous to a txt- file in Microsoft Notepad. An M-file is created in MATLAB text editor. M-files: You can save your programs (i.e., list of executable commands) as M-files. You can reopen and modify your program. They are useful for debugging (correcting errors) as you develop your programs (your technical computing tools). 11 Comments in programs Every time you write a program to be saved, it is helpful for you to comment (i.e., describe) it well. To insert a comment on a line in the editor or in the Command Window, use the comment operator %, then type your comment. MATLAB: will not run lines that begin with the comment operator (in the editor comments appear in green). Comments Comments allow you (and others) to more easily understand your program. When your lines of code are easy to understand, your code will be easier to use later. 12 Art of well-written code A well-written program is like literature; it contains comments explaining: what your program requires as input. what the variables in the program represent. what your program computes and displays. It is useful for you to add a set of header comments that include the name of the program, your name (as the programmer), and the date the program was created or modified. 13 Saving code in an M-File Open the editor by: Entering the command edit in the command window. Or click the white-sheet-of-paper icon in the upper left hand corner directly below file. Now enter the lines of code to find the volume of a cone: rr = 4 h = 12 v = (pi.*r.^2.*h)./3 REMARK: If you save it, add header comments and comments explaining what the program does. After you have typed in the code, save it as cone.m. 14 This is cone.m in the editor % % Tool to compute the volume of a cone. % A simple sample for a first lecture. % B.H.& Daniel........... January 2007 % rr = 4; % radius of the cone h = 12; % height of the cone v = (pi.*r.^2.*h)./3 % Volume of the cone
15 Execute an M-file as a Command Now execute (or run) the program by pushing F5, or by typing on the command line >> cone <Enter> or by clicking the run button. (Note that the run button looks like a page with a down arrow to its left. It can be found below help on the toolbar of the edit window.) If you entered the code as written on the previous slide you will get an error! What went wrong? Repair your program (Change rr = 4 to r = 4.), save it, and run it again. Now change the height to 24, save and run your program again. 16 Summary MATLAB can be used like a hand calculator to do arithmetic. You can define (or assign) variables with numbers and expressions to do calculations as illustrated by the volume-of-cone example. The advantage of saving programs as M-files is that you open it, make changes and/or execute it again without having to type it all over again. This concludes our overview of MATLAB and a taste of things to come! 17 Lecture 2 MATLAB fundamentals Variables, Naming Rules, Arrays (numbers, scalars, vectors, matrices), Arithmetical Operations, Defining and manipulating arrays 2007 Daniel Valentine. All rights reserved. Published by Elsevier. 18 Variables What are variables? You name the variables (as the programmer) and assign them numerical values. 19 Variable Naming Rules Must begin with a LETTER May only contain letters, numbers and underscores ( _ ) No spaces or punctuation marks allowed! Only the first 63 characters are significant; beyond that the names are truncated. Case sensitive (e.g. the variables a and A are not the same) 20 Which variable names are valid? 12oclockRock tertiarySector blue cows Eiffel65 red_bananas This_Variable_Name_Is_Quite_Possibly_Too_Lo ng_To_Be_Considered_Good_Practice_However _It_Will_Work % (the green part is not part of the recognized name) 21 Variable Naming Conventions There are different ways to name variables. The following illustrate some of the conventions used: lowerCamelCase UpperCamelCase underscore_convention
If a variable is a constant, some programmers use all caps: CONSTANT
It does not matter which convention you choose to work with; it is up to you. 22 23 In MATLAB, a variable is stored as an array of numbers. When appropriate, it is interpreted as a scalar, vector or matrix.
The size of an array is specified by the number of rows and the number of columns in the array, with the number of rows indicated first. Variables as Arrays scalar 1 1 vector n 1 or 1 n matrix n m 24 Scalars are 11 arrays. They contain a single value, for example: r = 6 r = 6 width = 9.07 width = 9.07 height = 5.3 height = 5.3 Scalars 25 Vectors A vector is a list of numbers expressed as a 1 dimensional array. A vector can be n1 or 1n. Columns are separated by commas (or spaces):
Rows are separated by semicolons: v = [1; 2; 3] v = [1; 2; 3] h = [1, 2, 3] h = [1, 2, 3] 26 m = [3.0, 1.8, 3.6; 4.6, m = [3.0, 1.8, 3.6; 4.6, - -2.0, 21.3; 0.0, 2.0, 21.3; 0.0, - -6.1, 12.8; 2.3, 0.3, 6.1, 12.8; 2.3, 0.3, - -6.1] 6.1] Matrices A matrix is a two dimensional array of numbers.
For example, this is a 43 matrix:
1 2 3 1 3.0 1.8 3.6 2 4.6 -2.0 21.3 3 0.0 -6.1 12.8 4 2.3 0.3 -6.1 Columns R o w s
27 m(2,3) m(2,3) Indexed-location of numbers in an array
Each item in an array is located in the (row, column). 1 2 3 1 3.0 1.8 3.6 2 4.6 -2.0 21.3 3 0.0 -6.1 12.8 4 2.3 0.3 -6.1 Columns R o w s
ans = 21.3000 28 Enter the following into MATLAB: Scalar:
Vectors:
Matrix: d = [5, 4, 3; 0, 2, 8] d = [5, 4, 3; 0, 2, 8] b = [1, 0, 2] b = [1, 0, 2] c = [1 0 2] c = [1 0 2] a = 1 a = 1 Examples 29 Examples Enter (input) the following matrix into MATLAB: -7 21 6 2 32 0 -5 0 -18.5 whiteRabbit = 30 Scalar Operations Operation Algebraic Syntax MATLAB Syntax Addition a + b a + b Subtraction a - b a b Multiplication a b a .* b Division a b a ./ b or a.\ b Exponentiation a b a .^ b
31 Array Operations Arrays of numbers in MATLAB can be interpreted as vectors and matrices if vector or matrix algebra is to be applied. Recall that matrices are mathematical objects that can be multiplied by the rules of matrices. To do matrix multiplication, you need to use the standard *, /, and ^ operators [without the preceding . (dot)]. They are not for array multiplication, division and exponentiation.
To deal with arrays on an element-by-element level we need to use the following array or dot-operators: .* , ./ and .^ 32 Array operations & dot-operators Because scalars are equivalent to a 11 array, you can either use the standard or the dot-operators when doing multiplication, division and exponentiation of scalars (i.e., of single numbers). It is okay for you to always use the dot- operators, unless you intend to perform vector or matrix multiplication or division. .* , ./ and .^ 33 Example:
z = x .* y results in [10, 6; 21, 32]; this is array multiplication z = x * y results in [17, 20; 43, 50]; this is matrix multiplication
So, do NOT forget the dot when doing array operations! (.* ./ .^) x = [2, 1; 3, 4] x = [2, 1; 3, 4] y = [5, 6; 7, 8] y = [5, 6; 7, 8] Array vs. Matrix Operations 34 Hierarchy of Operations Just like in mathematics the operations are done in the following order: Left to right doing what is in Parentheses & Exponents first, followed by Multiplication & Division, and then Addition & Subtraction last. An example: c = 2+3^2+1/(1+2) 1 st c = 2+3^2+1/3 c = 2+3^2+1/(1+2) 2 nd c = 2+9+1/3 c = 2+3^2+1/(1+2) 3 rd c = 2+9+0.33333 c = 2+3^2+1/(1+2) 4 th c = 11+0.33333 c = 2+3^2+1/(1+2) 5 th c = 11.33333 35 Hands-on Enter these two arrays into MATLAB:
Multiply, element-by-element, a b. Since this is an array operation, the .* multiplication operation is implied by the request. a = 10 5 5 2 9 0 6 8 8 b = 1 0 2 0 0 0 1 1 0 36 Defining & manipulating arrays All variables in MATLAB are arrays! Single number array & scalar: 1 1 Row array & row vector: 1 n Column array & column vector: n x 1 Array of n rows x m columns & Matrix: n m Naming rules Indexed by (row, column) Remark: vectors and matrices are special mathematical objects, arrays are lists or tables of numbers. 37 The equal sign assigns Consider the command lines: >> ax = 5; >> bx = [1 2]; >> by = [3 4]; >> b = bx + by; The equal sign (=) commands that the number computed on the right of it is input to the variable named on the left; thus, it is an assignment operation. 38 An array can be defined by typing in a list of numbers enclosed in square brackets:
Commas or spaces separate numbers.
Semicolons indicate a new row.
A = [12, 18, A = [12, 18, - -3] 3] or or A = [12 18 A = [12 18 - -3] 3] B = [2, 5, 2; 1 , 1, 2; 0, B = [2, 5, 2; 1 , 1, 2; 0, - -2, 6] 2, 6] Defining (or assigning) arrays A = 12 18 -3
C = [A; B] C = [A; B] D = [C, C] D = [C, C] Defining arrays continued You can define an array in terms of another array: C = 12 18 -3 2 5 2 1 1 2 0 -2 6
40 Create an array of zeros:
Create an array of ones:
Note: Placing a single number inside either function will return an n n array. e.g. ones(4) will return a 4 4 array filled with ones. E = zeros(3,5) E = zeros(3,5) F = ones(2,3) F = ones(2,3) Creating Zeros & Ones arrays E = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 F = 1 1 1 1 1 1 41 Index a number used to identify elements in an array Retrieving a value from an array:
G(3,2) G(3,2) G(2,1) G(2,1) G = [1, 2, 3; 4, 5, 6; 7, 8, 9] G = [1, 2, 3; 4, 5, 6; 7, 8, 9] Retrieving Values in an Array ans = 4 ans = 8 G = 1 2 3 4 5 6 7 8 9 42 You can change a value in an element in an array with indexing:
You can extend an array by defining a new element:
Notice how undefined values of the array are filled with zeros
A(2) = 5 A(2) = 5 A(6) = 8 A(6) = 8 Changing Values in an Array A = 12 5 -3 A = 12 5 -3 0 0 8 43 Colon notation can be used to define evenly spaced vectors in the form: first : last
The default spacing is 1, so to use a different increment, use the form: first : increment : last
The numbers now increment by 2 I = 1:2:11 I = 1:2:11 H = 1:6 H = 1:6 Colon Operator H = 1 2 3 4 5 6 I = 1 3 5 7 9 11 44 G(2,:) G(2,:) G(:,1) G(:,1) G(:,3) G(:,3) Extracting Data with the Colon Operator The colon represents an entire row or column when used in as an array index in place of a particular number.
G = 1 2 3 4 5 6 7 8 9 ans = 1 4 7 ans = 3 6 9 ans = 4 5 6 45 G(1,2:3) G(1,2:3) G(2:3,:) G(2:3,:) Extracting Data with the Colon Operator Continued The colon operator can also be used to extract a range of rows or columns:
G = 1 2 3 4 5 6 7 8 9 ans = 2 3
G = 4 5 6 7 8 9 46 J' J' J = [1 , 3, 7] J = [1 , 3, 7] Manipulating Arrays The transpose operator, an apostrophe, changes all of an arrays rows to columns and columns to rows.
J = 1 3 7 ans =
1 3 7 47 Manipulating Matrices Continued The functions fliplr() and flipud() flip a matrix left-to-right and top-to-bottom, respectively. Experiment with these functions to see how they work. 48 W = [1:5; 10:2:18; 6: W = [1:5; 10:2:18; 6:- -1:2] 1:2] Hands-on exercise: Create the following matrix using colon notation: W = 1 2 3 4 5 10 12 14 16 18 6 5 4 3 2
All three rows are evenly spaced The first row ranges from 1 to 5 in increments of 1 1:5 The second row ranges from 10 to 18 in increments of 2 10:2:18 The third row ranges from 6 to 2 in increments of -1 6:-1:2 All together:
49 Hands-on continued Create the following matrix using colon notation:
Transpose this matrix and assign it to variable Y. >> Y = x Extract the 2nd row from Y and assign it to variable Z. >> Z = Y(2,:) 50 Summary (1 of 2) Naming a variable: Start with letter followed by any combination of letters, numbers and underscores (up to 63 of these objects are recognized). Arrays are rows and columns of numbers. Array operations (element-by-element operations with the dot-operators) Hierarchy of arithmetic operations. 51 Summary (2 of 2) Command lines that assign variables numerical values start with the variable name followed by = and then the defining expression An array of numbers is the structure of variables in MATLAB. Within one variable name, a set of numbers can be stored. Array, vector and matrix operations are efficient MATLAB computational tools. 52 Lecture 3 Creating M-files Programming tools: Input/output (assign/graph-&-display) Repetition (for) Decision (if) 2007 Daniel Valentine. All rights reserved. Published by Elsevier. 53 T c Review Arrays List of numbers in brackets A comma or space separates numbers (columns) A semicolon separates row Zeros and ones Matrices: zeros() ones() Indexing (row,column) Colon Operator: Range of Data first:last or first:increment:last Manipulating Arrays & Matrices Transpose
54 Input Examples of input to arrays: Single number array & scalar: 1 1 >> a = 2 Row array & row vector: 1 n >> b = [1 3 2 5] Column array & column vector: n x 1 >> b = b % This an application of the transpose. Array of n rows x m columns & Matrix: n m >> c = [1 2 3; 4 5 6; 7 6 9] % This example is 3 x 3. 55 Basic elements of a program Input Initialize, define or assign numerical values to variables. Set of command expressions Operations applied to input variables that lead to the desired result. Output Display (graphically or numerically) result. 56 An example of technical computing Let us consider using the hyperbolic tangent to model a down-hill section of a snowboard or snow ski facility. Let us first examine the hyperbolic tangent function by executing the command: >> ezplot( tanh(x) )
We get the following graph: 57 Ezplot(tanh(x)) 58 Hyperbolic tangent: tanh(X) Properties (as illustrated in the figure): As X approaches Inf, tanh(X) approaches -1. As X approaches Inf, tanh(X) approaches +1. X = 0, tanh(X) = 0. Transition from -1 to 1 is smooth and most rapid (roughly speaking) in the range -2<X<2. REMARK: With this familiarity with tanh(X), let us apply it to solve the following problem. 59 Problem background Let us consider the design of a slope that is to be modeled by tanh(X). Consider the range -3<X<3, and assume the slope changes negligibly for |X|>3. Thus, for 3 < X < 3, 1 < tanh(X) < 1. We want to design a downhill slope such that in 10 meters the hill drops 2 meters. Thus, as shown next, the following formula is needed: y = 1 tanh(3*X/5). 60 Formula for snow hill shape 61 Problem statement Find the altitude of the hill at 0.5 meter intervals from -5 meters to 5 meters using the shape described and illustrated in the previous two slides. Tabulate the results. 62 Structure plan Structure plan Initialize the range of X in 0.5 meter intervals. Compute y, the altitude, with the formula: y = 1 tanh(3*X/5). Display the results in a table. Implementation of the structure plan Open the editor by typing edit in the command window. Translate plan into the M-file language. 63 This is from editor: It is lec3.m % % Ski slope offsets for the % HYPERBOLIC TANGENT DESIGN % by D.T. Valentine...January 2007 % % Points at which the function % is to be evaluated: % Step 1: Input x x = -5:0.5:5; % Step 2: Compute the y offset, % that is, the altitude: y = 1 - tanh(3.*x./5); % % Step 3: Display results in a table % disp(' ') % Skips a line disp(' X Y') disp([x' y']) Command window OUTPUT X Y -5.0000 1.9951 -4.5000 1.9910 -4.0000 1.9837 -3.5000 1.9705 -3.0000 1.9468 -2.5000 1.9051 -2.0000 1.8337 -1.5000 1.7163 -1.0000 1.5370 -0.5000 1.2913 0 1.0000 0.5000 0.7087 1.0000 0.4630 1.5000 0.2837 2.0000 0.1663 2.5000 0.0949 3.0000 0.0532 3.5000 0.0295 4.0000 0.0163 4.5000 0.0090 5.0000 0.0049 SOLUTION TO IN-CLASS EXERCISE 64 Use of repetition (for) Repetition: In the previous example, the fastest way to compute y was used. An alternative way is as follows: Replace: y = 1 - tanh(3.*x./5); % This is vectorized approach. With: for n=1:21 y(n) = 1 - tanh(3*x(n)/5); end Remark: Of course, the output is the same. 65 This is from editor: It is lec3_2.m % % Ski slope offsets for the % HYPERBOLIC TANGENT DESIGN % by D.T. Valentine...January 2007 % % Points at which the function % is to be evaluated: % Step 1: Input x x = -5:0.5:5; % Step 2: Compute the y offset for n=1:21 y(n) = 1 - tanh(3*x(n)/5); end % % Step 3: Display results in a table disp(' ') % Skips a line disp(' X Y') disp([x' y']) Command window OUTPUT X Y -5.0000 1.9951 -4.5000 1.9910 -4.0000 1.9837 -3.5000 1.9705 -3.0000 1.9468 -2.5000 1.9051 -2.0000 1.8337 -1.5000 1.7163 -1.0000 1.5370 -0.5000 1.2913 0 1.0000 0.5000 0.7087 1.0000 0.4630 1.5000 0.2837 2.0000 0.1663 2.5000 0.0949 3.0000 0.0532 3.5000 0.0295 4.0000 0.0163 4.5000 0.0090 5.0000 0.0049 SOLUTION TO IN-CLASS EXERCISE 66 Decision: Application of if Temperature conversion problem: Convert C to F or F to C.
67 % % Temperature conversion from C to F % or F to C as requested by the user % Dec = input(' Which way?: 1 => C to F? 0 => F to C: '); Temp = input(' What is the temperature you want to convert? '); % % Note the logical equals sgn (==) if Dec == 1 TF = (9/5)*Temp + 32; disp(' Temperature in F: ') disp(TF) else TC = (5/9)*(Temp-32); disp(' Temperature in C: ') disp(TC) end Decision: Application of if Temperature conversion problem: Convert C to F or F to C. SOLUTION:
68 Summary Introduced, by an example, the structure plan approach to design approaches to solve technical problems. Input: Assignment with and without input utility. Output: Graphical & tabular were shown. Illustrated array dot-operation, repetition (for) and decision (if) programming tools. 69