Lab 01: Introduction to MATLAB
What is MATLAB?
The name MATLAB stands for "MATrix LABoratory" and was originally designed as a tool for doing numerical computations with matrices and vectors. It has since grown into a highperformance language for technical computing. MATLAB, integrating computation, visualization, and programming in an easytouse environment, allows easy matrix manipulation, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs in other languages. Typical uses include:
 Math and Computation
 Modeling and Simulation
 Data Analysis and Visualization
 Application Development
 Graphical User Interface development
Getting Started
Window Layout
MATLAB development IDE can be launched from the icon created on the desktop. The main working window in MATLAB is called the desktop. When MATLAB is started, the desktop appears in its default layout:
The following tools are managed by MATLAB desktop, although not all of them appear by default when you first start
 Current Folder  This panel allows you to access the project folders and files.
 Command Window  This is the main area where commands can be entered at the command line.It is indicated by the command prompt (>>).
 Workspace  The workspace shows all the variables created and/or imported from files.
 Command History  This panel shows or rerun commands that are entered at the command line.
By default, the Command History window closes after a statement is selected or the Esc key is pressed. To keep the Command History window open, in the Command History window, click and then select either Detach or Dock. If the Command History window is closed while detached or docked, go to the Home tab, and in the Environment section, click Layout. Then, under Show, click Command History and select either Docked or Popup.
1.1 MATLAB Basics
MATLAB Basics
Variables
Variables
MATLAB does not require a command to declare variables. A variable is created simply by directly allocating a value to it. All variables are created with double precision unless specified and they are matrices.
>> v = 3
v =
3
After these statements, the variables are 1x1 matrices with double precision.
>> 23 + 18 # no declarations needed
ans =
41
>> product = 18 * 32.64 # mixed data type
product =
5.875200000000000e+02
>> product = 18 * 555.24; # semicolon suppresses output of calculation's result
>> product
product =
9.994320000000000e+03
MATLAB Variable Names
 Variable names are CASE SENSITIVE.
 Variable names can contain up to 63 characters (as of MATLAB 6.5 and newer).
 Variable names must start with a letter followed by letters. digits, and underscores ( _ ).
 MATLAB has several keywords that cannot be used as programmerdefined variable names.
The following table provides a list of keywords. The list of keywords can be found by entering the command "iskeyword" on the Command Window.
break  case  catch  classdef  continue 
else  elseif  end  for  function 
global  if  otherwise  parfor  persisyent 
return  spmd  switch  try  while 
Special Variables and Constants
Command  Description 
ans  Temporary variable containing the most recent answer. If you do not assign an output variable to an expression, MATLAB automatically stores the result in ans. 
eps  This variable name is short for “epsilon”. It is the smallest difference between two numbers that can be represented on the computer. (Smallest incremental number) 
i, j  The imaginary unit 
inf  Infinity. Calculations like n/0, where n is any nonzero real value, result in inf. 
NaN  NotaNumber, indicates an undefined numerical result. Expressions like 0/0 and inf/inf result in a NaN, as do arithmetic operations involving a NaN. n/0, where n is complex, also returns NaN. 
pi  The number ( = 3.1415926535897...) 
realmin  The smallest usable positive real number. 
realmax  The largest usable positive real number. 
computer  Computer type. 
version  MATLAB version string. 
clock  This special variable contains the current date and time in the form of a 6element row vector containing the year, month, day, hour, minute, and second. 
date  Contains the current data in a character string format, such as 24Nov1998. 
Here are several examples that use these values in MATLAB expressions.
>> x = 2 * pi;
>> A = [3+2i 78i];
>> tol = 3 * eps;
Matrices and Vectors
Matrices and Vectors
The fundamental unit of data in MATLAB is the array. An array is a collection of data values organized into rows and columns. Arrays can be classified as either vectors, matrices or scalars.
 The term "vector" is usually used to describe an array with only one dimension.
 Row Vector: an array with n elements in a single row (1 x n matrix)
>> a = [1 2 3 4]
a = 1x4
1 2 3 4  Column Vector: an array with m elements in a single column (m x 1 matrix)
>> b = [1;2;3]
b = 3x1
1
2
3
 Row Vector: an array with n elements in a single row (1 x n matrix)
 The term "matrix" is usually used to describe an array with two or more dimensions.
>> A = [1 , 2 , 3 ; 4, 5, 6]
A =
1 2 3
4 5 6  A single value, called a Scalars, is represented as a 1 x 1 matrix. A scalar can be created in MATLAB as follows:
>> a_value = 23
a_value =
23
In this text, we will use the term "vector" when discussing onedimensional arrays and the term "matrix" when discussing arrays with two or more dimensions.
1.2 MATLAB Operators and Special Characters
 Arithmetic Operators
 Relational Operators
 Logical Operators/Functions
 Special Characters
 String and Character Formatting
 Arithmetic Operators
 Relational Operators
 Logical Operators/Functions
 Special Characters
 String and Character Formatting
Arithmetic Operators
Arithmetic Operators
Symbol  Role 

+  Addition 
+  Unary plus 
  Subtraction 
  Unary minus 
*  Matrix multiplication 
/  Matrix right division 
^  Matrix power 
Symbol  Role 

.*  Elementwise multiplication 
.\  Elementwise left division 
.^  Elementwise power 
.'  Transpose 
'  Complex conjugate transpose 
Array Operations
Array Operations
There are two types of arithmetic operators in MATLAB:
 Matrix arithmetic operators, which are governed by the rules of linear algebra.
 Vector arithmetic operators, which are performed elementwise.
Matrix Operations
Operation  Role Played 

A + B  Scalar and array addition 
A  B  Scale and array subtraction 
A * B  Scale multiplication and multiplication in matrix algebra. (The number of columns in A must equal the number of rows in B.) 
A / B  Right division: scale division and division in matrix algebra. A / B = A * inv(B) where A and B are matrices 
A \ B  Left division. A \ B = inv(A) * B, where A and B are matrices. 
A ^ b  Scalar exponentiation and matrix exponentiation in matrix algebra (A^{b}) 
A'  Transpose 
Elementwise Operations
Elementwise Operations
Evaluated element by element
Operation  Role Played 

a .* b  Elementbyelement multiplication of a and b. Both arrays must be the same shape, or one of them must be a scalar.(dot multiply or dot star). 
a ./ b  Elementbyelement right division of a and b. Both arrays must be the same shape, or one of them must be a scalar. A ./ B = [A(i,j) / B(i,j)], where A and B are arrays [dim(A) = dim(B)] 
a .\ b  Elementbyelement left division of a and b Both arrays must be the same shape, or one of them must be a scalar. A .\ B = [B(i,j) / A(i,j)], where A and B are arrays [dim(A) = dim(B)] 
a .^ b  Elementwise power. Both arrays must be the same shape, or one of them must be a scalar.(dot power or dot caret). A .^ B = [a(i,j)^{b(i,j)}], for arrays A and B 
a.'  Array transpose (nonconjugated transpose) 
Example: Array Operations
Give A and B matrices:
A =
1 2 3
4 5 6
7 8 9
B =
3 5 2
5 2 8
3 6 9
Addition
>> X = A + B
X =
4 7 5
9 7 14
10 14 18
Subtraction
>> Y = A  B
Y =
2 3 1
1 3 2
4 2 0
Product
>> Z = A * B
Z =
22 27 45
55 66 102
88 105 159
Transpose
>> T = A'
T =
1 4 7
2 5 8
3 6 9
Example: ElementWise Operations
Array operation are very different from matrix operations:
>> A = [1 2; 3 4];
>> B = [5 6; 7 8];
>> A * B
19 22
43 50
But:
>> A .* B
5 12
21 32
The use of "." — "Element" Operation
>> A = [1 2 3 ; 6 2 8 ; 1 4 2]
A =
1 2 3
6 2 8
1 4 2
>> x = A(1 , : )
x =
1 2 3
>> y = A( 3 , :)
y =
1 4 2
>> b = x .* y
b =
1 8 6
>> c = x ./ y
c =
1.000 0.5000 1.5000
>> d = x .^ 2
d =
1 4 9
 When you multiply a scalar times an array you may use either operator ( * or .* ), but when you multiply two arrays together they mean something quite different.
 Unfortunately, when you divide a scalar by an array you still need to use the ./ syntax, because the / means taking the matrix inverse to MATLAB. As a general rule, unless you specifically are doing problems involving linear algebra (matrix mathematics), you should use the dot operators.
Relational Operators
Relational Operators
MATLAB supports six relational operators.
Operation  Role Played 
<  Less than 
<=  Less than or equal to 
>  Greater than 
>=  Great than or equal to 
==  Equal to 
~=  Not equal to 
>> A = [2 7 6 ; 9 0 5 ; 3 0.5 6];
>> B = [8 7 0 ; 3 2 5 ; 4 –1 7];
>> A == B
ans =
0 1 0
0 0 1
0 0 0
Logical Operators/Functions
Logical Operators/Functions
MATLAB supports three logical operators.
Operation  Role Played 
~  logical NOT 
&  logical AND 
  logic OR 
>> u = [1 0 2 3 0 5];
>> v = [5 6 1 0 0 7];
>> u & v
ans =
1 0 1 0 0 1
>> u  v
ans =
1 1 1 1 0 1
>> ~u
ans =
0 1 0 0 1 0
MATLAB also supports some logical functions.
functions  Role Played 
xor(A,B)  Logical Exclusive OR. 
or (A,B)  Logical OR. 
and (A,B)  Logical AND. 
not (A)  Logical NOT. 
any (X)  Returns 1 if any element of X is true or nonzero. any function operates columnwise on matrices. 
all (X)  Returns 1 if all elements of X are true or nonzero. all operates columnwise on matrices. 
isnan (X)  Returns 1 at each NaN in X. 
isinf (X)  Returns 1 at each infinity in X. 
isfinite (X)  Returns 1 at each finite value in X. 
isempty (X)  Returns 1 if X is an empty array. An empty array has no elements. 
>> a = 1;
>> b = 1;
>> xor(a, b)
ans =
0
>> A = [0 1 2 ; 3 5 0];
>> all (A)
ans =
0 1 0
>> V = [5 0 8];
>> any (V)
ans =
1
Special Characters
Special Characters
String and Character Formatting
Some special characters can only be used in the text of a character vector or string. You can use these special characters to insert newlines or carriage returns, specify folder paths, and more.
Use the special characters in this table to specify a folder path using a character vector or string.
1.3 Math Functions
Math Functions
Common Computations
The functions listed in the following table accept either a scalar or a matrix of x values.
functions  Role Played  MATLAB Example 
abs (x)  Finds the absolute value of x.  >> abs (3) ans = 3 
sqrt (x)  Finds the square root of x.  >> sqrt (85) ans = 9.2195 
nthroot (x,n)  Finds the real n_{th} root of x. This function will not return complex results.  >> nthroot(2,3) ans = 1.2599 
sign (x)  Returns a value:

>> sign (8) ans = 1 
rem (x, y)  Computes the remainder of x / y.  >> rem (25, 4) ans = 1 
exp (x)  Computes the value of e^{x}, where e is the base for natural logarithms, or approximately 2.7183.  >> exp (10) ans = 2.2026e+04 
log (x)  Computes ln(x), the natural logarithm of x (to the base e).  >> log (10) ans = 2.3026 
log10 (x)  Computes log_{10} (x), the common logarithm of x (to the base 10).  >> log10(10) ans = 1 
Trigonometric Functions
MATLAB includes a complete set of the standard trigonometric functions and the hyperbolic trigonometric functions. Most of these functions assume that angles are expressed in radians.
functions  Role Played 
sin (x)  Finds the sine of x when x is expressed in radians, sin(x). 
cos (x)  Finds the cosine of x when x is expressed in radians, cos(x). 
tan (x)  Finds the tangent of x when x is expressed in radians, tan(x). 
asin (x)  Finds the arcsine sin^{1}(x), or inverse sine, of x, where x must be between 1 and 1. 
sinh (x)  Finds the hyperbolic sine of x when x is expressed in radians, sinh(x). 
asinh (x)  Finds the inverse hyperbolic sin of x, sinh^{1}(x). 
sind (x)  Finds the sin of x when x is expressed in degrees, sin(xº). 
asind (x)  Finds the inverse sin of x and reports the result in degrees, sin^{1}(x). 
Practice Exercises
Exe 1: MATLAB Expressions
Suppose that a = 1 and b = 3. Evaluate the following expressions using MATLAB.
Exe 2: ans Variable
Typing the following MATLAB statements into the Command Window:
4 * 5
a = ans * pi
b = ans / pi
ans
 What are the results in a, b, and ans?
 What is the final value saved in ans?
 Why was that value retained during the subsequent calculations?
Exe 3: Operators
As you perform the following calculations, recall the difference between the * and .* operators, as well as the / and ./ and the ^ and .^ operators:
 Define the matrix a = [2.3 5.8 9] as a MATLAB variable.
 Find the sine of a.
 Add 3 to every element in a.
 Define the matrix b = [5.2 3.14 2] as a MATLAB variable.
 Add together each element in matrix a and in matrix b.
 Multiply each element in a by the corresponding element in b.
 Square each element in matrix a.
 Create a matrix named c of evenly spaced values from 0 to 10, with an increment of 1.
 Create a matrix named d of evenly spaced values from 0 to 10, with an increment of 2.
 Use the linspace function to create a matrix of six evenly spaced values from 10 to 20.
 Use the logspace function to create a matrix of five logarithmically spaced values between 10 and 100.
Exe 4: Math Function
Calculate the following (remember that mathematical notation is not necessarily the same as MATLAB notation):
 for
 for ; let change in steps of
 for ; let x change in steps of 0.2.
 Find the cosine of 45º.
 Convert the angle from degrees to radians, and then use cos function.
 Use the cosd function.
 Find the angle whose sine is 0.5. Is your answer in degrees or radians?
 Find the cosecant of 60. You may have to use the help function to find the appropriate syntax.