G

Lect01-Intro2matlab-A

Semester Overview: Introduction to MATLAB

  • Approximately 9 weeks dedicated to MATLAB.
  • Topics include:
    • Interactive Computation (MATLAB as a calculator)
    • Graphing & Data Visualization
    • Introduction to Programming in MATLAB
      • Numerical Analysis
      • Symbolic Math
      • Simulink
      • Introduction to Standards in EE/CompE

Numerical Analysis Applications/Projects

  • Approximately 6 weeks.
  • Covers statistics and curve-fitting.
    • Lecture & Lab Experiment for each topic (Statistics, Curve-fitting, Gaussian Elimination).

Lecture 1 – Introduction to MATLAB - Overview

  • Getting started in MATLAB:
    • Starting/Quitting
    • Comment lines (%)
    • The desktop environment
    • Navigating the workspace
    • Keeping track of variables
  • Built-in operations, constants, and functions.
  • Controlling the display format.
  • Complex arithmetic.
  • Getting help (help, lookfor, doc).
  • Creating arrays, accessing sub-arrays, and deleting parts of arrays.
  • Matrix Operations & Functions & Solving Systems of Equations
  • Special Matrices
  • Element-by-element Operations
  • Nodal Analysis with Conductance Matrices
  • Includes Exercise Sets: ES#01, ES#02, ES#03, ES#04, ES#05

What is MATLAB?

  • MATLAB: "MATrix LABoratory," created by The Mathworks, Inc.

    • Designed for operating on vectors and matrices.
    • Includes built-in functions and special-purpose toolboxes.
      • statistics, controls, communications, DSP, symbolic math, etc.
    • Contains well-known numerical packages (e.g., LINPACK, EISPACK).
  • Platform-independent.

  • High-end mathematics package for interactive computation and data visualization

    • Interactive: no compilation or linking needed.
  • Case-sensitive (e.g., Vel is different from vel).

Getting Started with MATLAB

  • Start: Double-click the MATLAB icon or go to Start menu ➜ all programs ➜ MATLAB.
    • This opens the Command Window with the input prompt: >>.
    • Student Edition prompt: EDU >>
  • Enter commands after the prompt and press Enter.
  • Quit: Type quit or use the "X" in the top right corner.
  • Use percent sign (%) for comments:
    • At the start of the line: entire line is a comment.
    • In the middle of the line: everything after "%" is a comment.

The MATLAB Desktop

  • MATLAB R2021b opens with three windows:
    • Current Directory/Folder Window (left, top)
    • Command Window (right side, large)
    • Workspace Window (left, bottom)
  • Plots & Apps tabs (discussed later).
  • Command History window:
    • Displays recent commands, useful for corrections.
    • Open by typing: >> commandhistory

The MATLAB Desktop - 3 Windows:

Current Folder/Directory, Command, & Workspace

Operators in MATLAB

  • Order of Operations:
    • Exponentiation (^)
    • Multiplication (*) and division (/) and left division (\)
    • Addition (+) and subtraction (-)
  • Scalar Examples
    • >> 2 + 3
    • >> 2 + 3 * 5 % note order of operations
    • >> 3 + 2 ^ 5 % again, note the order of operations
    • >> 3 – 2 * 4 + 3 ^ 2
    • >> 4 + 25 / 5 % usual meaning for 25 ÷ 5 = 5
    • >> 4 + 25 \ 5 % 25 into 5 = 5/25 = .2
      • Left division: a\b = b / a

Built-in Constants and Special Variables

  • pi: \pi = 3.14159…
  • eps: Smallest number such that 1 + # > 1 (spacing between floating-point numbers)
  • i or j: \sqrt{-1}
  • ans: Temporarily stores the most recently calculated value.
  • NaN: Not a Number (e.g., 0/0).
  • inf: ∞, e.g., 5/0
  • realmin: Smallest positive floating-point number.
  • realmax: Largest positive floating-point number.
  • Examples:
    • >> 2 * PI % remember that MATLAB is case-sensitive
    • >> 2 * pi
    • >> ans ^ 2 % equals (2*pi)^2
  • More examples:
    • >> 1/0
    • >> i ^ 2
    • >> eps % about 2*10^-16
  • Assignment Operator (=)
    • >> x = 3 % let variable x have value 3
    • >> x = x + 2 % replace x by the old x value, plus 2
  • Examples
    • >> y = 9
    • >> y = y ^2 + 10
    • >> x = 5, w = 3 % It’s O.K. to put several commands in one line, separated by a comma.
    • >> z = x * w

Built-in Functions

  • sqrt - square root
  • exp - exponential (e.g., ex = exp(x))
  • log - natural log (base e)
  • log10 - log base 10
  • log2 - log base 2
  • sin - sine
  • sinh - hyperbolic sine
  • asin - inverse sine
  • asinh - inverse hyperbolic sine
  • cos - cosine
  • cosh - hyperbolic cosine
  • acos - inverse cosine
  • acosh - inverse hyperbolic cosine
  • tan - tangent
  • cot - cotangent
  • sec - secant
  • abs - absolute value
  • conj - complex conjugate
  • fix - round towards 0
  • floor - round towards (-inf)
  • ceil - round towards (inf)
  • size - dimensions of an array
  • det - determinant of a matrix
  • inv - inverse of a matrix
  • eig - eigenvalues/vectors of a matrix
    *Note: Trig functions require arguments in radians; angular measure answers are also in radians.

More Built-in Functions – EE/CompE Related

  • sind - sine of angle given in degrees
  • asind - inverse sine, answer in degrees
  • cosd - cosine of angle in degrees
  • acosd - inverse cosine, answer in degrees
  • Similar functions exist for tan, sec, csc
  • mag2dB - converts magnitude data to decibels: ydb = 20 log10(y)
  • dB2mag - converts decibel data to linear magnitude: y = 10.^(ydb/20)
  • pol2cart - Converts from polar form to Cartesian form (or from cylindrical to Cartesian for 3D case)
  • cart2pol - Converts numbers from Cartesian form to polar form (or from Cartesian to cylindrical for 3D case)
  • Similarly: see cart2sph, sph2cart (for spherical ↔ Cartesian conversion) and hex2dec, dec2hex (for hexadecimal ↔ decimal conversion)

Examples with Built-in Functions

  1. Find the natural log of 3 (math notation: ln(3)) in MATLAB:
    • >> log(3) % ans = 1.0986
  2. Find common log of 3 (math notation: log(3)) in MATLAB:
    • >> log10(3) % ans = .4771
  3. Evaluate: e^5.6
    • >> exp(5.6) % ans = 270.4264
  4. Find: tan(30°)
    • >> tand(30) % ans = 0.5774
  5. Write in polar form: 5 + 7j
    • >> [theta, r] = cart2pol(5,7) % theta = 0.9505, r = 8.6023
    • Polar form: 8.6023 e^{.9505j}
      *Note: MATLAB won’t actually put the number in polar form; you have to do that part by hand.

Getting Around in the Workspace

If you make a mistake:

  • Press enter to get a new prompt, and type the desired command again; or,
  • Use the up-arrow (↑) to move up to a previous entry, and the left and right arrows (←, →) to move to the part of line you want to edit.
  • Use the delete key to remove a character in front of the cursor, or the backspace key to remove a character behind the cursor.
  • Use the escape key to clear an entire line
  • Use Ctrl+C to stop an operation and get a new command line prompt (Very useful if you are in an infinite loop.)

Getting Around in the Workspace (Cont.)

  • Use a semi-colon (;) at the end of a line or command to suppress the display (called the echo) of the result on the screen
  • Put several commands on one line, separating them with commas (or semi-colons to suppress the display of the result on the screen)
  • Use spacing to make your code more readable
  • Use an ellipsis (…) to continue a long line of code to the next line
  • Sometimes in MATLAB you will see your results (output) flash across the screen so quickly that you can’t read them. To control the flow of the output display, use the command:
    • >> more on (to display 1 screen at a time)
    • >> more off (to get back to the default streaming display)

Controlling the Numeric Format of the Display

(Display Format vs. Computational Precision)

  • All computations in MATLAB are done in double precision.
  • Some variations on the FORMAT command are listed below:
    • FORMAT: Default. Same as SHORT.
    • FORMAT SHORT: Scaled fixed point format with 4 decimal digits.
    • FORMAT LONG: Scaled fixed point format with 15 dec. digits.
    • FORMAT SHORT E: Floating point format with 4 dec. digits.
    • FORMAT LONG E: Floating point format with 15 dec. digits.
    • FORMAT SHORT G: Best of fixed or floating point format with 5 digits.
    • FORMAT LONG G: Best of fixed or floating point format with 15 digits.
    • FORMAT SHORT ENG: 5 signif. digits; power is a multiple of 3.
    • FORMAT LONG ENG: 16 signif. digits; power is multiple of 3.
    • FORMAT BANK: Format for dollars & cents
    • FORMAT HEX: Hexadecimal display
  • Practice: Type in the vectors x = [7/3 1.3579e-6 pi], and y = [1/3 exp(1) 10^-5 2222.34], followed by the various format commands above. (Ask for the values of x and y after typing each format; e.g., format long, x, y)
  • FORMAT COMPACT: Suppresses extra line-feeds.
  • FORMAT LOOSE: Puts the extra line-feeds back in.

Exercise Set 1

  1. Calculate:
    • a. 234 - 4
    • b. 4\pi – 183
    • c. \log(37)
    • d. \ln(37)
    • e. \sin(1)
    • f. \cos(60^\circ)
    • g. e^2
    • h. \tan^{-1}(1/2)
    • i. \log_2(64)
    • j. \frac{13}{5}
    • k. \sqrt[3]{\frac{3}{32}} - 5
  2. Find the area of a circle with radius 5 inches.
  3. Use the formulas V = IR (Ohm’s Law) and P = \frac{V^2}{R} to find the voltage (V) across and power (P) dissipated by a resistor if the current (I) through the resistor is 5 amps and the resistor value R is 100 ohms.
    Recall that (per mathematical convention) log means log base 10, or common log; ln means log base e, or natural log – compare to the MATLAB definitions on p. 10 of this lecture.
    Answers:
  4. 279,826.58
  5. –5,819.43
  6. 5682
  7. 6109
  8. 8415
  9. 5
  10. 3891
  11. 4636
  12. 6
  13. 6
  14. -1.0029
  15. 5398 sq. in.
  16. V = 500 volts, P = 2500 Watts

Complex Arithmetic

  • MATLAB Notation: It’s OK to write a + bi “as is”, without a multiplication sign (*) between the b and the i
  • Use either i or j for the square root of (-1)
  • +, -, *, and / are performed as with real numbers
  • Example of a work session with complex arithmetic
    • >> x = 3 + 4i; y = 3 – 6i;
    • >> x + y
      • ans = 6 – 2i
    • >> x*y
      • ans = 33.0000 - 6.0000i
    • >> x/y
      • ans = -0.3333 + 0.6667i

Complex Arithmetic: Rectangular and Polar Notation

  • Use abs() to find the magnitude, and angle() to find the phase angle (in radians) of a complex number, as shown below:
    • >> x = 3 + 4i; w = abs(x); z = angle(x);
    • >> w, z
      • ans = 5
      • ans = .9273
  • Recall from pp. 11 – 12, you can also use the commands
    • cart2pol (for changing Cartesian coordinates to polar coordinates)
    • pol2cart (for changing polar coordinates to Cartesian coordinates, as shown below (answers not shown):
    • >> [theta, rho] = cart2pol(3, 4 )
    • >> [x1, y1] = pol2cart(.9273, 5)
      *Note: specify 2 output arguments

Circuit Example

  • Given v = 120 \cos(120 \pi t), and using phasor transforms, find

    • (a) the impedance seen by the source and
    • (b) the current through C1.
      Solution
      % Let f = frequency, w = ang. freq,
      % Vo = Source amplitude
      % SFA = Source phase angle,
      % C1, C2, R, & L: the element values.
      format compact;
      f=60; Vo=120; SFA=0; C1=4.7E-6; C2=1.5E-6; R=470; L=0.65;
      w=2*pi*f;
      ZC1=1/(j*w*C1); ZC2=1/(j*w*C2); ZL= j*w*L; % Element Impedances
  • (a) Input Impedance (seen by the source):

    • Zin = ZC1 + 1/(1/R + 1/(ZL+ZC2))
  • (b) Current through C1

    • I1 = (Vo*exp(j*SFA)) / Zin

Getting Help

  • To find help when you don’t know the name of the function you want, use the lookfor command, with syntax: lookfor keyword
    • Ex: say I want to make a graph, but I don’t know how; type
      >> lookfor graph
      % Usectrl Cto stop
    • MATLAB will return with several commands/functions that are related to graphing.
  • If you know the name of a particular function, but need help with the syntax, use the help command, with syntax:help function`
    • Ex: say I want to use cart2pol (changing Cartesian coordinates to polar), but I don’t remember the syntax; type
      >> help cart2pol
    • MATLAB will return with the syntax and a description of the function.

Getting help (cont.)

  • If you know the name of a particular function you want, but need help with the syntax and/or thorough documentation about the mathematical algorithm employed, use the doc command, with syntax: >> doc function
    • Example: continuing with the Cartesian to polar example from the previous page, to get more information and examples about using the cart2pol function, type
      >> doc cart2pol
    • MATLAB will return with an HTML page (from the Help Browser) giving the syntax, an example, and a thorough description of the function, including the algorithm employed.
      *Note that this will only work if you included documentation when MATLAB was installed on your computer, or if you have the documentation CD in the CD drive.

Keeping Track of Variables in MATLAB

  • The who command will display a list of all defined variables. whos will also display the size of each variable.
  • Typing the name of a variable and pressing enter will display the current value of the variable, or an error message if no such variable exists.
  • The clc command clears the command window, but leaves the value of any variables unchanged.
  • clear var1 var2 clears the value of variables var1 and var2 from memory. (O.K. to use * for wild card, as in clear a*)
  • The clear command clears the value of all variables from memory.

Exercise Set 2

(1 of 2) Do these problems individually but check your answers as a pair.

  1. Find the angle, q, for the number: x = 1 + 5j
  2. Find the magnitude of the complex number x above.
  3. Write x in the form r e^{jq}; i.e., write it in polar form (by typing it in Word).
  4. Change to polar form: y = 5 + 12 j (Type the answer in Word.)
  5. Change to Cartesian Coordinates: 2e^{j 60^\circ}
  6. Change to Cartesian Coordinates: 4 e^{.2j}
  7. Simplify: \frac{4+j}{5 – 2j}, and write the answer in polar and rectangular form. (Type the answer using the superscript in Word.)
  8. Simplify: (4+2j) * (2 + 5j), and write the answer in polar and rectangular form. (Type the answer using the superscript in Word.) Watch the units!

Exercise Set 2 (2 of 2)

  1. Use phasors and MATLAB to find the impedance seen by the source and the current coming out of the source if the source voltage is: V(t) = 10 \sin(200 \pi t).
    Introduction to Arrays (e.g., vectors & matrices) and the Creation of Row Vectors
  • An array is a rectangular arrangement of objects (m rows, n columns), that may or may not have the math properties of a matrix
  • Vectors and matrices are special type of arrays
  • Scalars are 1 x 1 matrices, and thus 1 x 1 arrays
  • Use square brackets to describe a row vector; e.g.,
    • >> x = [0, 1, 4]
    • >> x = [0 1 4]
  • If the vector components are equally spaced, use the syntax x = [1st component : spacing : last component]
    • e.g., >> x = [0 : 0.1 : 10] Po-0lop for the vector containing 0, .1, .2, … , 9.9, 10 Good habit: don’t suppress the echo for (short) matrices and vectors.

Creating Arrays (e.g., Vectors and Matrices)

  • Use square brackets, with semicolons to move from row-to-row, to define a column vector; e.g.,
    >> x = [0; 1; 4]
    x =
    0
    1
    4
  • To define an array or matrix, use square brackets as for a vector, with semi-colons (;) to separate the rows, e.g.,
    >> a = [1 2 0; 4 5 6; 7 8 1]
    a =
    1 2 0
    4 5 6
    7 8 1

Creating Arrays (Cont.)

and Concatenation

  • To take the transpose* of a matrix, say matrix a from the previous page, and to name the result “atransp”, try:
    >> atransp = a’ % apostrophe sign or single quote
  • The stringing or chaining together of several appropriately sized vectors/matrices is called concatenation. Some examples:
    • >> y = [2 3 7]’, newmatrix = [x y] % concatenating x and y
    • >> A = [1 2 3;4 5 6; 7 8 9]
    • >> newmatrix2 = [newmatrix A]
    • >> B = [10 11 12], newmatrix3 = [A; B] %conc., B under A
      *Recall that when you take the transpose of a matrix, every row becomes a column and every column becomes a row.

Accessing Arrays (Vectors and Matrices)

  • To access a particular element (say the element in row 2, column 3) of the matrix mvalues as defined below, we use the following notation to name the desired row and column:
    >> mvalues = [1 2 3 4; 5 6 7 8; 9 10 11 12]
    >> mvalues23 = mvalues(2, 3)
  • To access a particular row (say row 2) of the matrix mvalues as defined above, we use the colon (:) to select all the elements in the specified row:
    >> mrow2 = mvalues(2, :)
  • To access a particular column (say column 2) of the matrix mvalues as defined above, we use the colon (:) to select all of the elements in the specified column:
    >> mcolumn2 = mvalues(:, 2)

Accessing Arrays (Vectors and Matrices), cont.’

  • A particular element of a matrix can also be accessed with a single index, instead of giving the row and column number. The single index value is found by counting the elements of the array, going down the columns.
    Example:
    >> b = [1 2 3; 4 5 6; 7 8 9]
    b =
    1 2 3
    4 5 6
    7 8 9
    >> b(7)
    ans = 3
    We say that MATLAB is “column-dominant”, because the default numbering of elements is obtained by counting down the columns. Columns will also take precedence over rows in other ways.

Accessing Vectors

  • Elements of either row or column vectors can be accessed with just a single coordinate:
  • Examples
    • >> x = [1 2 3 4]; % row vector
    • >> x(3)
      • ans = 3
    • >> y = [1 2 3 4]‘ % column vector
    • >> y(2)
      • ans = 2

Accessing Subarrays, Submatrices

  • Now we have already defined:
    a = 1 2 0
    4 5 6
    7 8 1
  • Say we want the “lower-right” 2 x 2 submatrix, containing: [5 6; 8 1]; since the desired submatrix is in rows 2-3 and columns 2-3 of the original a matrix, we type:
    >> a(2:3, 2:3) % specifying the rows & columns desired
    Ans = 5 6
    8 1

Deleting Parts of an Array

  • To delete a particular row or column of a matrix, we set that row or column to a null vector, [ ].
  • Example: Enter the matrix
    >> B = [ 1 2 3; 4 5 6; 7 8 9]
    Now to delete row 2, type:
    >> B(2, :) = [ ] % deletes row 2 (all columns)
    Now to delete column 3, type:
    >> B( : , 3) = [ ] % deletes column 3 (all rows)

Exercise Set 3 (1 of 2)

  1. Enter the matrices: A = \begin{bmatrix} 2 & 0 & 7\ 1 & 5 & 1\ 4 & 1 & 2 \end{bmatrix}, B = \begin{bmatrix} 9 & 0 & 1\ 2 & 1 & 4\ 3 & 2 & 3 \end{bmatrix}
    • a. Define the row vector a as the first row of matrix A, by selecting the elements from A.
    • b. Define the column vector b as the first column of matrix B, by selecting the elements from B.
    • c. Define scalar c as the element in row 2, column 3 of matrix B, by selecting the element from B.
    • d. Define the submatrix C as the 2 x 2 upper-left submatrix of A, by selecting the elements from A.
    • e. Construct a row vector x, consisting of: 1, 1.08, 1.16, …, 1.88
    • f. Construct a column vector y that is the transpose of vector x.
    • g. Concatenate matrices A and B, with B underneath A.

Exercise Set 3 (2 of 2)

  1. Enter the vectors: x = [1 2;4 3], y = [2; 3]
    • a. concatenate x and y so that y is to the left of x;
    • b. concatenate x and y so that y is underneath x.
  2. Create a new matrix, A_new, containing only the 1st and 2nd rows of the given matrix A (from problem 1), by deleting row 3 of A.

Matrix Operations Review

  • Addition, subtraction and multiplication of matrices work in the obvious way in MATLAB, giving the correct answers.
    • A matrix with m rows and n columns is said to be of dimension (m, n) or m x n.
    • Recall the matrices and/or vectors can only be added or subtracted if they are of the same size or dimension.
      Addition/subtraction example:
      >> a = [1 2 4; 3 1 2], b = [0 1 2; 5 1 3]
      >> c = a + b, d = a – b

MATLAB Example: Same Problem, Regular Math:

>> a = [1 1; 2 2]
a =
1 1
2 2
>> a + 5
a + 5 = ????
ans = 6 6
7 7
MATLAB calls this scalar expansion, since it actually expands the scalar addend (5) to the required matrix size to make matrix addition possible. Subtraction works the same way.

Matrix Operations Review

  • Caution: Recall that matrix multiplication for matrices A and B is only defined under the following condition:
    • If A is of dimension (mA, nA) and B is of dimension (mB, nB)
    • And if nA = mB (i.e., the inner dimensions agree);
    • Then A*B is of size (mA, nB) (i.e., given by the outer dimensions)
      Matrix Multiplication Example:
      >> A = [3 2; 4 6], B = [1; 2] % note: inner dim. agree
      >> A*B % note size of answer

Matrix Operations (Cont.)

  • Attempting to multiply matrices for which multiplication is not defined (because the inner dimensions don’t agree) yields a common error message (shown below in green):
  • Incorrect multiplication example:
    >> A = [2 3; 1 4], B = [1 4 6 5]
    A = 2 3
    1 4
    B = 1 4
    6 5
    >> A*B
    ??? Error using ==> mtimes Inner matrix dimensions must agree.
    The most common error message in MATLAB, for most engineers.

Matrix Division???

  • Division of matrices is not defined in mathematics.
  • However, MATLAB defines 2 “division-like” operations for matrices A and B.
  • Right Division: A/B (normal-looking fraction bar)
    • When matrix A-1 exists (i.e., if A is non singular), this means:
      • A/B = B * inv(A) (right-multiplying by the inverse)
      • This is the solution, x, to the system of equations: xA = B.
  • Left Division: A\B (backwards-looking fraction bar)
    • When matrix A-1 exists (i.e., if A is non-singular), this means:
      • A\B = inv(A)*B (left-multiplying by the inverse)
      • This is the solution, x, to the system of equations: Ax = B

Array/Matrix Functions

  • To find the determinant of the square matrix called mA as given below, try:
    >> mA = [1 2 0; 4 5 6; 7 8 1]
    >> det(mA)
  • To find the length of a (row or column) vector, we use the function length(vector_name); e.g., to find the length of row vector B defined on p. 39, type:
    >> length(B)
  • To find the geometric or Euclidean length* of vector B, type:
    >> norm(B)

of elements, not the geometric length Recall the geometric length of vector [b1 … bn] is: \sqrt{b1^2 + … + bn^2}

Array/Matrix Functions (Cont.)

  • To find the number of rows and columns of a matrix, say mA, above, type:
    >> size(mA)
    (Use a 2nd argument of 1 if you just want the # of rows, or 2nd argument of 2 if you just want the # of columns; e.g., size(mA,2).)
  • To find the eigenvalues and eigenvectors of the square matrix, mA, type: >> [V D] = eig(mA)
    • The eigenvalues are on the diagonal of matrix D;
    • The eigenvectors are the columns of matrix V.
    • Note that you must specify two outputs, V and D; if you just type >> eig(mA), you will only get the eigenvalues.

Array Functions: sum and prod

  • When applied to a (row or column) vector, the function sum( ) computes the sum of the elements in the vector.