0% found this document useful (0 votes)
3 views57 pages

Mat Lab

This document is a MATLAB ShortCourse Handout from Texas Tech University, designed to introduce users to the basics of MATLAB 9.4, Release 2018a. It covers essential topics such as performing computations, managing variables, creating matrices and vectors, and using built-in functions, along with an overview of the MATLAB desktop environment. The handout also provides information on obtaining help, saving workspaces, and accessing MATLAB resources.

Uploaded by

zumanji
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views57 pages

Mat Lab

This document is a MATLAB ShortCourse Handout from Texas Tech University, designed to introduce users to the basics of MATLAB 9.4, Release 2018a. It covers essential topics such as performing computations, managing variables, creating matrices and vectors, and using built-in functions, along with an overview of the MATLAB desktop environment. The handout also provides information on obtaining help, saving workspaces, and accessing MATLAB resources.

Uploaded by

zumanji
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TECHNOLOGY

SUPPORT MATLAB
SHORTCOURSE HANDOUT

Texas Tech University | Heide Mansouri


MATLAB ShortCourse Handout

Table of Contents
Introduction .................................................................................................................... 4
Course Objectives ........................................................................................................ 4
Texas Tech University MATLAB Campus License ............................................. 5
The MATLAB System ................................................................................................... 5
Overview of the MATLAB Desktop ......................................................................... 6
Command Window ....................................................................................................... 7
Workspace Window ..................................................................................................... 8
Ways to Get Help, using the Command-line ..................................................... 9
To Perform Simple Computations ........................................................................ 10
Variable Names ........................................................................................................... 12
Some MATLAB function descriptions .................................................................. 13
Commands for Managing variables and the workspace.............................. 13
To Check for MATLAB Keywords: ......................................................................... 14
Built-In Functions ....................................................................................................... 14
Making Mistakes ......................................................................................................... 15
Numeric Display Format .......................................................................................... 15
Preferences ................................................................................................................... 16
Precedence of Arithmetic Operations ................................................................. 17
Some MATLAB Special Characters ....................................................................... 17
To Suppress Output with Semicolon (;) ............................................................ 17
Creation of Matrices and Vectors ......................................................................... 18
Overwriting Variables ............................................................................................... 20
Using the Colon Notation (:).................................................................................. 20
Workspace Window Setting .................................................................................... 21
Opening the Variable Editor ................................................................................... 22
Accessing Single Elements in a Matrix............................................................... 25
Creating Matrices, using Functions ..................................................................... 27
Building Elementary Matrices and Arrays (all lowercases) ........................ 28
Adding and Subtracting Matrices ......................................................................... 29
Basic Arithmetic Operations in MATLAB ............................................................ 29

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 2
MATLAB ShortCourse Handout

Element –by-Element (Element-wise) Operations ........................................ 30


Matrix Transpose ........................................................................................................ 31
Vector Products and Transpose ............................................................................ 32
Multiplying Matrices ................................................................................................... 32
Roots of a Polynomial ............................................................................................... 33
Solving the System of Linear Equation AX=b ................................................. 34
Creating Symbolic Variables and Expressions ................................................ 35
The syms command: ................................................................................................ 36
Using the solve function .......................................................................................... 37
Integration .................................................................................................................... 38
Symbolic Integration, using int Function .......................................................... 40
To compute integrals using the int function .................................................... 41
Definite Integrals Example: ................................................................................... 42
Graphics Window ........................................................................................................ 42
Specifying Graph’s Line, Mark, and Color Styles ........................................... 45
Cylinder Function........................................................................................................ 47
To save your graph: .................................................................................................. 47
Cones are special cylinders: .................................................................................. 47
Creating Symbolic Variables and Functions (Calculus Example)............. 50
Importing Excel Spreadsheet Data, using the Import Tool ....................... 52
Some Important Commands ................................................................................. 55
The M-Files.................................................................................................................... 55
Saving and loading Files .......................................................................................... 56
The Difference between *.m and *.mat files in MATLAB ........................... 57
Online Resources ........................................................................................................ 57

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 3
MATLAB ShortCourse Handout

MATLAB ShortCourse

Copyright 2012-2018 Heide Mansouri, Texas Tech University. ALL RIGHTS


RESERVED. Members of Texas Tech University or Texas Tech Health Sciences Center
may print and use this material for their personal use only. No part of this material
may be reproduced in any form without written permission from Heide Mansouri, the
author.

Credit: This document is adapted mostly from MATLAB User’s Guide Documentation.

Introduction
MATLAB, short for MATrix LABoratory, is an interactive matrix-based software
package; designed for engineering and scientific applications. The MATLAB Desktop
is a set of tools for managing files, variables, and applications associated with
MATLAB.

This ShortCourse is designed to acquaint you with the basics of MATLAB 9.4,
Release 2018a under Windows. The mathematical background needed for
this ShortCourse, is college algebra. This ShortCourse is meant to serve as a quick
way to learn MATLAB. For more detailed information, please consult the official
MATLAB documentation.

Course Objectives
After completing this ShortCourse, you should be able to
 Perform Basic MATLAB Operations;
 Perform simple computations;
 Work with variables and functions;
 Work with Matrices and Vectors ( in MATLAB, all variables are matrices);
 Create matrices and vectors;
 Perform some basic linear algebra;
 Work with array operators;
 Use the Symbolic Integration to calculate integrals;
 Create Plots;
 Solving the System of Linear Equation AX=b;
 Compute integrals using the int function; and
 Import Excel Spreadsheet Data, using the Import Tool.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 4
MATLAB ShortCourse Handout

Texas Tech University MATLAB Campus License


 The latest version of MATLAB software and its top 50 toolboxes is available
at no cost to TTU students, faculty, and staff members for download @
[Link]
 MATLAB’s semiannual cycle for releasing updates are March, and September
of each year.
 If you have any questions or need assistance, please contact IT Help Central
at 742-HELP (4357) or ithelpcentral@[Link].
o Support is available for TTU customers from the MathWorks
[Link]

The MATLAB System


The MATLAB system consists of five main parts:

1. MATLAB Language - is a high-level matrix/array language with control flow


statements, functions, data structures, input/output, and object-oriented
programming features.
2. MATLAB Desktop Tools - is the set of tools that help you work and manage
the variables in your workspace and importing/exporting data. Desktop Tools

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 5
MATLAB ShortCourse Handout

include the MATLAB desktop and Command Window, an editor and


debugger, a code analyzer, and browsers for viewing the Workspace.
3. MATLAB Graphics - includes high-level commands for two-dimensional
and three-dimensional data visualization, image processing, animation, and
presentation graphics.
4. MATLAB Mathematical Function Library -is collection of computational
algorithms ranging from elementary functions like sum, sine, cosine, and
complex arithmetic, to more sophisticated functions like matrix inverse, and
more.
5. MATLAB Application Program Interface (API) - is a library that allows
you to write C/C++ and FORTRAN programs that interact with MATLAB.

Starting MATLAB
 Start -> ALL Programs -> MATLAB -> MATLAB R2018a
 MATLAB displays the Command Window (in the center) that is used to enter
commands and display text-only results.
 The Current Folder Pane is on the left.
 The Graphics window and Editing window will automatically open, when
needed.
 The MATLAB Workspace consists of the set of variables built up and stored
in memory during a MATLAB session. The Workspace browser enables you to
view, change, and plot MATLAB workspace values.
 The Command History Window displays a log of statements you ran in the
current and previous MATLAB sessions. All entries remain until you delete
them.

Overview of the MATLAB Desktop


 The following components appear at the top of the MATLAB desktop:
o Toolstrip contains the HOME, PLOTS and APPS tabs. Additional tabs,
such as EDITOR, PUBLISH and VARIABLE, appear in the Toolstrip as
needed to support your workflow.
o Quick access toolbar displays frequently used options such as cut,
copy, paste and help.
o Current folder toolbar enables you to specify the current working
directory.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 6
MATLAB ShortCourse Handout

o Search Documentation box allows you to search the documentation.


 The desktop (in its default layout) displays these windows:
o Current Folder enables you to access the contents of the current working
directory. Use the options in the current folder toolbar to change the
current working folder.
o Command Window lets you execute commands at the command line,
indicated by the prompt (>>).
o Workspace allows you to explore data that you create or import from
files. You can view the contents of the workspace using whos command.
o Command History allows you to view or rerun commands that you
entered at the command line.

Command Window
 Use the Command Window to enter data, run MATLAB code, and display
results.
 Enter statements at the prompt >>, which is also known as the Command-
line.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 7
MATLAB ShortCourse Handout

 You can perform calculations in the Command Window similar to the way you
perform calculations on a scientific calculator.
 To reset the MATLAB Desktop to default layout, in the HOME tab, choose
Layout, and then select Default.

Workspace Window
 Workspace is a graphical user interface that allows you to view and manage
the contents of the workspace in MATLAB.
 To edit variables, double-click the variable in the Workspace browser. The
variable displays in the Variables Editor, where you can view the full
contents and make changes.
 You add variables to the workspace by using functions, running MATLAB code,
and loading saved workspaces.
 From the Workspace browser, you can select variables to view, modify, or
plot.
 Workspace variables do not persist after you exit MATLAB. Therefore, use
your data for later use with the save command,

save [Link]

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 8
MATLAB ShortCourse Handout

 Saving preserves the workspace in your current working folder in a


compressed file with a .mat extension, called a MAT-file.
 To clear all the variables from the workspace, use the clear command.
 Restore data from a MAT-file into workspace using load command,

load [Link]
 To open the Workspace browser if it is not currently visible, do either of the
following:
o On the HOME tab, in the Environment section, click Layout. Then,
under Show, select Workspace.
o Type workspace at the Command Window prompt.

Ways to Get Help, using the Command-line


 There are several commands that allow you to get help:
o demo has demos of several options in MATLAB
o doc provides more in-depth information
o clc Window will clear the Command Window.
Heide Mansouri Updated: April 5, 2018
Texas Tech University Page 9
MATLAB ShortCourse Handout

 You can transfer any command from the Command history


window to Command Window by double-clicking (which also
executes the command), or by clicking and dragging the line of
code into Command Window.
o quit or exit terminates MATLAB.

Examples:
>> help sqrt <ENTER>
>> doc plot <ENTER>
>> help log <ENTER>

Search Syntax and Tips


 Find keywords in the documentation by entering text in the Search box on
the Desktop or in the Help browser.

 When you view pages linked from the search results, search terms appear
with highlights. To clear the highlights, press the Esc key.
Searches can include the following operators:
”“ Exact phrase. Example: "plot tools" finds pages that contain plot
tools, in that sequence, with no words between them.
* Wildcard. Requires at least two non-wildcards characters, and cannot
appear at the start of a keyword or in an exact phrase.
Example: plot* finds plot, plot3, and plotting.
OR Boolean OR. Example: plot OR graph finds pages with
either plot or graph.
NOT Boolean NOT. Example: "plot tools" NOT "time series" finds pages
with plot tools but excludes pages with time series.
AND Boolean AND. Implied when no operator is present between
keywords. Example: plot AND tools is equivalent to "plot" "tools".
The Help browser search evaluates NOT operators first, OR operators second,
and AND operators last. For example, "plotting tool" OR "plot tools" NOT "time
series" AND workspace.

To Perform Simple Computations


 At prompt >> Type a command and then press the Enter key.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 10
MATLAB ShortCourse Handout

 In the second example the trigonometric function sine and the constant 
are used.
 In MATLAB they are named sin and pi, respectively. Note that the results of
these computations are saved in variables whose names are chosen by the
user.
 If they will be needed during your current MATLAB session, then you can
obtain their values typing their names and pressing the Enter key. For
instance,

 To clear the Command Window type clc and then press the Enter key.

Note: MATLAB uses a default variable name ans if an expression is


typed at the prompt and it is not assigned to a variable. To change
this to a Result Variable (for example), us UP Arrow key (to recall
previous line of command), and Then LEFT Arrow key to modify the
command. This is very useful, especially if a long expression is entered with an error,
and it is desired to go back to correct it.
Example:

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 11
MATLAB ShortCourse Handout

Variable Names
 A variable name starts with a letter (a-z or A-Z), followed by any number (0-
9), letters, digits, or underscores ( _ ).
 Have a maximum length of 31 characters.
 MATLAB software is case sensitive, so A and a are not the same variable.
 You cannot define variables with the same names as MATLAB keywords, such
as if or end (for a complete list, run the iskeyword command).

Examples of variable names:


 xxxxxxxxx
 pipeRadius
 widgets_per_box
 mySum
 Mysum. Note: mySum and mysum are different variables. (MATLAB
is case sensitive).

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 12
MATLAB ShortCourse Handout

Some MATLAB function descriptions

Note: Functions are all lower cases!

Commands for Managing variables and the workspace

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 13
MATLAB ShortCourse Handout

To Check for MATLAB Keywords:

Built-In Functions
Functions are files that can accept input arguments and return output arguments.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 14
MATLAB ShortCourse Handout

To use the Built-in Functions

Note:
 log(x) computes the natural logarithm of x
 log10(x) is the base 10 logarithm
 log2(x) is the base 2 logarithm

Making Mistakes
 When you make a mistake, you cannot just overwrite your command on the
same line after you have executed it.
 Instead, you can enter the correct command on a new line, and then execute
the new version.
 Or- recall previous commands by pressing the up- and left-arrow keys on
your keyboard. Press the arrow keys either at an empty command line or
after you type the first few characters of a command.

Numeric Display Format


 The default format of numbers is called short (4 digits after the decimal
point.)
 To display more digits click on HOME tab, click the Preferences button, and
then change the Numeric Format for Text Display.
 You can also select a new format from within the Command Window. For
instance, the following command format long changes a current format to
the format long (15 digits after the decimal point).

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 15
MATLAB ShortCourse Handout

 To display 2 decimal digits, use format bank.


 To close MATLAB type exit, in the Command Window and next press Enter
or Return key.
 Or, from the File menu in the MATLAB's toolbar click on Exit MATLAB option.
All unsaved information residing in the MATLAB Workspace will be lost.
Note: Changing display format does not change the accuracy of your results.

Preferences
 HOME-> Preferences

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 16
MATLAB ShortCourse Handout

Precedence of Arithmetic Operations

Some MATLAB Special Characters

To Suppress Output with Semicolon (;)


Results of intermediate steps can be suppressed with semicolons. The variables
created or calculated; will show in Workspace, but do not show in Command
Window.

Example:
Assign values to x, y, and z, but only display the value of z in the command window:

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 17
MATLAB ShortCourse Handout

Multiple Statements per Line


 Use commas or semicolons to enter more than one statement at once.
 Commas allow multiple statements per line without suppressing output.

Creation of Matrices and Vectors


 For manual entry, the elements in a vector are enclosed in square brackets []
 When creating a row vector, separate elements with a space or comma (,)
 To create a column vector, separate columns with a semicolon (;)

Assigning Elements to a Matrix


When assigning elements to matrix, row elements are separated by spaces, or
commas, and columns are separated by semicolons (;)

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 18
MATLAB ShortCourse Handout

Or-

Creates a 3-by-3 matrix and assigns it to a variable A.

Transpose Operator ('), using a single quotation


The transpose operator converts a row vector to a column vector (and vice versa),
and it changes the rows of a matrix to columns.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 19
MATLAB ShortCourse Handout

Overwriting Variables
Once a variable has been created, it can be reassigned.

Using the Colon Notation (:)


To simplify the creation of large vectors, you define a vector by specifying the first
entry, in increment (step value), and last entry, using the colon operator.

Note: in this case the brackets [] are not necessary to define the vector.

If you want to look at the first four entries of the vector, then you use the following
notations:

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 20
MATLAB ShortCourse Handout

More examples:

MATLAB Data Types


 MATLAB data (numerical variables) is placed into “data container” in the
form of Workspace variables.
 All Workspace variables organize data into some form of array.
 2-D numerical arrays (matrices) organize observations and measured
variables by rows and columns, respectively.
 Multidimensional arrays – an extension of the normal 2-dimentional matrices.
 Cell and structure arrays – which organizes data of different types, sizes,
units, etc.

Workspace Window Setting


 For each variable or object, the Workspace Browser shows: The Name,
Value, Class, Statistics, Min, Max, Range, etc.
 To set the Workspace Window to show more about the variables, right-click
on the bar with column labels.
 Check size.
 The yellow grid-like symbol indicates the variable “A” is a 3-by-3 matrix, and
variables “fun” and “s” are 1-by-1 single values (one row by one column).

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 21
MATLAB ShortCourse Handout

About the Variable Editor


The Variable Editor enables you to:
 Display variables in the current workspace.
 View and edit values of one or two-dimensional arrays, character strings, cell
arrays, structures, and objects and their properties. Right-click the variable in
the Workspace, then Edit Value (or-double-click the variable to Open the
Editor Window).
 View the contents of multidimensional arrays.
 Copy and paste data values.
 Edits you make in the Variable Editor immediately update the variable in the
workspace.

Opening the Variable Editor


 If the Workspace browser is not open, select Layout -> Workspace.
 Create some workspace variables, for example:
A=magic(4);
x = 0:.1:4*pi;
y = sin(x);
 Then, in the Workspace browser, select the variable you want to open.
 Use (Shift + click) or (Ctrl + click) to select multiple variables, or use (Ctrl
+ A) to select all variables to open.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 22
MATLAB ShortCourse Handout

 Click the Open Selection button on the toolbar.


o For one variable, you can also open it by double-
clicking it.
 The Variable Editor opens, displaying the values for the selected variable.
 The class and size of the value appear below the toolbar, and for some
classes, include a link to the help for that class.
 Click the Plot Selector to create a graph of the selected variables.
 Click a tabbed document to display a different variable that is open in the
Variable Editor.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 23
MATLAB ShortCourse Handout

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 24
MATLAB ShortCourse Handout

Accessing Single Elements in a Matrix


 To reference a particular element in a matrix, specify its row and column
number using the following syntax, where A is the matrix variable. Always
specify the row first and column second: A (row, column). For example, for a
4-by-4 magic square A,

 A magic square matrix is an n-by-n matrix constructed from integers 1


through n2 with equal rows, column, and diagonal sums, where n  3

 You would access the element at row 4, column 2 with

Accessing Multiple Elements


 For the following 4-by-4 matrix A, it is possible to compute the sum of the
elements in the fourth column of A by typing

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 25
MATLAB ShortCourse Handout

 You can reduce the size of this expression using the colon operator.
 Subscript expressions involving colons refer to portions of a matrix.
 The expression A(1:m, n) refers to the elements in rows 1 through m of
column n of matrix A.
 Using this notation, you can compute the sum of the fourth column of A more
succinctly: sum(A(1:4, 4))

Specifying All Elements of a Row or Column, using Colon (:)


 The colon by itself refers to all the elements in a row or column of a matrix.
 Using the following syntax, you can compute the sum of all elements in the
second column of a 4-by-4 magic square A:

 By using the colon with linear indexing, you can refer to all elements in the
entire matrix.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 26
MATLAB ShortCourse Handout

 This example displays all the elements of matrix A, returning them in a


column-wise order:

Creating Matrices, using Functions


MATLAB has dozens of functions that create different kinds of matrices. To create a
3-by-3 symmetric, use the pascal(3):

Note: A Pascal (n) returns the Pascal matrix of order n: a symmetric positive
definite matrix with integer entries taken from Pascal's triangle.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 27
MATLAB ShortCourse Handout

Building Elementary Matrices and Arrays (all lowercases)

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 28
MATLAB ShortCourse Handout

Adding and Subtracting Matrices


 Addition and subtraction of matrices is defined just as it is for arrays, element
by element.
 Addition and subtraction require both matrices to have the same dimension,
or one of them to be a scalar.

Basic Arithmetic Operations in MATLAB

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 29
MATLAB ShortCourse Handout

Note that MATLAB has two divisions operators / - the right division and \ - the left
division. They do not produce the same results

Element –by-Element (Element-wise) Operations


Arithmetic operations can be performed on each entry of an array, but using a period
‘ . ‘ before certain operators such as multiplication, division, and exponentiation.
Then corresponding entries can be obtained, using the operations ‘ .* ‘ , ‘ . / ‘ , and
‘ . ^ ’ respectively.

Examples:

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 30
MATLAB ShortCourse Handout

Matrix Transpose
 Transposition turns a row vector into a column vector:

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 31
MATLAB ShortCourse Handout

Vector Products and Transpose


 If x and y are both real column vectors, then the product x*y is not defined,
but the two products x'*y and y'*x are the same scalar.

 A row vector and a column vector of the same length can be multiplied in
either order.
 The result is either a scalar( the inner product), or a matrix (the outer
product ) :

Multiplying Matrices
 MATLAB uses a single asterisk (*) to denote matrix multiplication (inner
dimension of matrices should match).
 The next two examples illustrate the fact that matrix multiplication is not
commutative; that is, AB is usually not equal to BA:

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 32
MATLAB ShortCourse Handout

Roots of a Polynomial

 MATLAB can compute the roots of a function r = roots(p) where


o p is a row vector with the n+1 coefficients of the polynomial
o r is a column vector with the roots of the polynomial

Examples:
 The polynomial X2 -2X -3 is represented in MATLAB software as p = [1-2-3].
Remember to include all coefficients, even if 0.

 Given the roots of a polynomial, the polynomial itself can be calculated.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 33
MATLAB ShortCourse Handout

Solving the System of Linear Equation AX=b


If A is an n-by-n matrix and B is a column vector with n elements, or a matrix with
several such columns, then X = A\b (A inverse times b) is the solution to the
equation AX = b.

Consider:

𝑥
Where X=[𝑦] is a column vector of unknowns x, y, z. Then, we need to solve
𝑧
AX = b, where

One way to solve this system is X=inv(A)*b. A better way, from both and
execution time and numerical accuracy standpoint, is to use the matrix division
operator X=A\b (using the backslash operator, also called left division). This
produces the solution using Gaussian Elimination, without forming the inverse.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 34
MATLAB ShortCourse Handout

Creating Symbolic Variables and Expressions


 Symbolic Math Toolbox™ provides tools for solving and manipulating
symbolic math expressions such as differentiation, integration, and
equation solving.
 Symbolic expressions are used to simplify mathematical expressions.
 Symbolic objects enable you to perform mathematical operations in the
MATLAB workspace analytically, without calculating numeric values (gives us
symbolic equations as results, rather than matrices or vectors).
 You can use sym or syms to create symbolic variables in one function call (to
declare variables as symbolic objects).

Example:
To declare f (x, y) as a symbolic function that accepts two arguments x, and y:

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 35
MATLAB ShortCourse Handout

Or-

Then, to compute the function value at point x=1 and y=2:

Note: You can use sym or syms to create symbolic variables.

The syms command:


• Does not use parentheses and quotation marks: syms x
• Can create multiple objects with one call
• Serves best for creating individual single and multiple symbolic variables

The sym command:


• Requires parentheses and quotation marks: x = sym('x')
• When creating a symbolic number with 15 or fewer decimal digits, you
can skip the quotation marks: f = sym(5)
• Creates one symbolic object with each call.
• Serves best for creating symbolic numbers and symbolic expressions.
• Serves best for creating symbolic objects in functions and scripts.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 36
MATLAB ShortCourse Handout

Using the solve function

Symbolic math functions can be used to solve a single equation, a system of


equations, and differential equations. You can use the double equation sign (==) to
define an equation. Then you can solve the equation by calling the solve function.
Solve function; solves the equation for specified variable.

For example: to solve x2-1

Or-

Note: double equal sign (==) is a Relational Operator, and is used when the first
input is equal to the second input (two-input mode).

Symbolic Expressions Example


 For example, create the following expression f, and the plot of f for the values
of variable x from -15 to 15:

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 37
MATLAB ShortCourse Handout

Integration
 The int function can be used for definite integration by passing the limits over
which you want to calculate the integral.
 If f is a symbolic expression, then int(f) attempts to find another symbolic
expression, F, so that diff(F) = f. That is, int(f) returns the indefinite
integral or antiderivative of f (provided one exists in closed form).
 Here are some examples of integration of expressions containing those
variables.
Note: If MATLAB is unable to find an answer to the integral of a function f, it just
returns int(f).

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 38
MATLAB ShortCourse Handout

Some integration of expressions containing those variables

Definite integration

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 39
MATLAB ShortCourse Handout

Examples of Integration

Symbolic Integration, using int Function

The int command can be used for definite integration by passing the limits over
𝑏
which you want to calculate the integral ∫𝑎 𝑓(𝑥)𝑑𝑥 = 𝑓(𝑏) − 𝑓(𝑎) , we write int(x,
a, b)

Syntax:
 int(expr, var) - computes indefinite integral of the expr with respect to
variable var.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 40
MATLAB ShortCourse Handout

 int(expr,var,a,b) - computes the definite integral of expr with respect to var


1
from a to b. For example to find ∫0 𝑥 7 𝑑𝑥

To compute integrals using the int function


 To find the integral of f= sin(x)/x and visualize the sine integral function from
-15 to 15:

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 41
MATLAB ShortCourse Handout

Definite Integrals Example:

 Let

 Use ezplot to plot for

 Use the Symbolic Toolbox to find

Graphics Window
Let’s create 2 arrays of x and y. A semicolon suppresses the output from the
commands. Then we use the Plot Command: plot(x,y), to create a linear 2-
dimensional x-y plot (y vector versus x vector).

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 42
MATLAB ShortCourse Handout

You can also generate a plot of one or more variables, using the PLOTS tab on the
Toolstrip.

Tips:
 Use plot function, to create linear 2-D plots.
 Use plots3 function, to create 3-D plots.
 Use ezplot function, to plot an expression, equation, or function f
(univariate).

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 43
MATLAB ShortCourse Handout

2-D Plots

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 44
MATLAB ShortCourse Handout

Specifying Graph’s Line, Mark, and Color Styles

3-D Plots

Note:
.* symbol is used for element-by-element
multiplication.
You may want to enable zooming graph

tools to see greater detail in a


small area of the graph.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 45
MATLAB ShortCourse Handout

The command mesh(Z) creates a three dimensional plot of the elements of the
matrix Z.

Try:
mesh(eye(10))
Surf(eye(10))

Common Graphics Functions in MATLAB

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 46
MATLAB ShortCourse Handout

Cylinder Function
 The function cylinder is used for plotting a surface of revolution. The
command cylinder(r, n) is used where, parameter r stands for the vector that
defines the radius of cylinder along the z-axis and n specifies a number of
points used to define circumference of the cylinder.

 For example, Plots a cone with the base radius


equal to one and the unit height.

0.8

0.6

0.4

0.2

0
1

0.5 1

0 0.5
0
-0.5
-0.5
-1 -1

To save your graph:


 File -> Save As type (*.fig)
 Specify a name for your file -> click OK.

Cones are special cylinders:

Example:

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 47
MATLAB ShortCourse Handout

 The cylinders are produced by cylinder function, all have unit height.
 The argument of cylinder is a vector which contains the distance from the wall
of the cylinder to the vertical axis at equally spaced points. This should
explain why we get cones with [1 0] (distance 1 to axis at base and distance
0 at top) and why [0 1] is oriented in the opposite direction.

Note: “hold on” holds the current plot and all axis properties so that subsequent
graphing commands add to the existing graph. “hold off” returns to the default
mode whereby plot commands erase the previous plots and reset all axis
properties before drawing new plots.

Example:

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 48
MATLAB ShortCourse Handout

Cylinder Function Examples:

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 49
MATLAB ShortCourse Handout

Creating Symbolic Variables and Functions (Calculus Example)

 To create the function Enter the following commands


(using syms to create symbolic variable x):

This returns f = (3*x^2 + 6*x - 1)/(x^2 + x - 3)


You can plot the graph of f by entering ezplot(f). This displays the following plot.

Sort Command
The Sort command arranges the values of a vector into ascending order, and if it is
used with a matrix; it sorts each column of a matrix in ascending order, unless you
specify.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 50
MATLAB ShortCourse Handout

Example:
Suppose that the vector A represents the distribution of measurements:
A=[68,83,61,70,75,82,57,51,76,85,62,71,96,78,76,68,72,75,83,93]
To create a bar graph, and a histogram of these measurements:
1. Sort the data to create a bar graph of scores
2. Create a histogram of the scores.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 51
MATLAB ShortCourse Handout

Importing Excel Spreadsheet Data, using the Import Tool


 On the HOME tab, in the VARIABLE section, click Import Data
 Browse to find [Link] file (In SC folder).
 Select Import Data -> Select just the data (not the name of the variables)
to be imported (change the selection of data to B2:C13).
 Select the Numeric Matrix from the drop down Imported data list.
 Import Matrix -> Import Data. Once the Import Wizard has completed the
import, the matrix name untitled will appear in Workspace window. Close the
Import window.
 Rename this Matrix to Data.
Heide Mansouri Updated: April 5, 2018
Texas Tech University Page 52
MATLAB ShortCourse Handout

Example: A sample of weather data collected for two successive years is given in
the following table:

 Then write a MATLAB script to find the average peak wind speed by month,
and by year.
 Find the highest peak wind speed by the month of year. Open the Script
Editor, and then type the following codes:

 Then click the RUN button, to run the script. Functions sum, max, and
mean will be applied to each column and a row vector of results are returned.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 53
MATLAB ShortCourse Handout

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 54
MATLAB ShortCourse Handout

Some Important Commands


 To run MATLAB demos:
o Type demo in the command window, and press the Enter key.
 To clear Windows:
o Type clc to clear the contents of the command window. This removes
all lines in your Command Window.
o Type clf to clear the contents of the figure window
 To clear Variables:
o Type clear to clear the contents of the workspace. This deletes all
stored variables in your Workspace.
 To close all of the figure generated:
o Type close all.

Note: it is a good idea that at the beginning of every program to include:


 close all – closes all of the figures that you have generated in your program.
 clear all – deletes all stored variables in your workspace.
 clc – removes all lines in your command window.

This will clear all the work done in previous sessions of the program.

The M-Files
 If you wish to execute repeatedly some set of commands, and possibly
change input parameters as well, then you should create a script M-File.
 To make the m-file click on New Script button on the File group.
 Once you are done with typing your codes, click on Save, in the MATLAB
Editor Window and select Save As…
Note: Your file should be saved in the directory that is in MATLAB's search
path.

Example:
Begin by creating the following script file (using the Script Window):

• Save it as test1.m.

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 55
MATLAB ShortCourse Handout

• Click the Run button, and it will ask for a number.


• Type a number and press the Enter key – it will square it and display the
result.
• Or- in Command window, type test1 and press the Enter key, and follow the
instruction.

Script Example
The body mass index script, using the metric system:
• Let’s Open another blank Script file (Home -> New Script), and then type the
following program:

 File -> Save As -> test2 -> Save.


 Click Run.
 Close The Editor window.

Saving and loading Files


 To save your Workspace variables to a file (binary formatted MAT-file).
o Right-click the Workspace -> Save -> Choose a name for your file
(file-name) and click on Save button.
Remember that the file you save (*.mat) will be stored in the current
directory (C:users\Username\Documents\MATLAB for example).

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 56
MATLAB ShortCourse Handout

 Another way of saving your workspace is to type save filename in the


Command Window. The command save filename saves only the variables.
 To load contents of the file named filename into MATLAB's workspace type
load filename in the Command Window.
Practice:

The Difference between *.m and *.mat files in MATLAB


 Files with .m extension contain MATLAB code, either in the form of a script
or a function.
 Files with .mat extension contain MATLAB formatted data, and can be
loaded from or written to these files using the functions load and save.

Quitting the MATLAB Program


 To end your MATLAB session, select File > Exit MATLAB in the desktop
 Or- type quit in the Command Window.

Online Resources

 Up and Running with MATLAB video training courses


[Link]
 MATLAB Examples [Link]
 FREE MATLAB interactive course from MATLAB Academy
[Link]

Where to Get Help


 Texas Tech University has site licenses for MATLAB software, and as a
member of the TTU community, you have the right to have full 24 hours
support from MATLAB.
 If you need help from me, please e-mail [Link]@[Link]. Or call
834-2935 to make an appointment.
Please e-mail your comments or suggestions to: [Link]@[Link]

Heide Mansouri Updated: April 5, 2018


Texas Tech University Page 57

You might also like