You are on page 1of 43

Lecture #1

Getting Started with MATLAB


ENGR 15100: Software Tools for Engineers
Steve Naumov (Instructor)

Lecture Overview
This set of lecture notes describes:

What is computer programming


What is MATLAB
Starting MATLAB and MATLABs User Interface
Working with MATLABs Command Window
Arithmetic Operations with Scalars
Elementary Built-in Functions
Defining Scalar & String Variables
Managing Variables
Script Files
Errors in Script Files
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Computer Languages
What is a computer language?

An artificial language designed to express computations


designed to be executed by a machine, particularly a computer

General Categories of Computer Languages

Machine Language Strings of numbers arranged in a


particular order dictating computations to be performed

The actual sequence of instructions executed by a central processing


unit (CPU or brain) of a computer

Example:
+1300042774
+1400593419
+1200274027

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Computer Languages (contd)


Broad Categories of Computer Languages

Assembly Language English-like abbreviations representing


elementary computer operations. Translated to machine
language with assemblers
Example:
LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY

High-Level Language Codes/commands similar to everyday


English by utilizing notation similar to mathematical notation.
Translated to assembly/machine language with compilers
Example:
grossPay = basePay + overTimePay;
circle_area = pi * radius * radius;

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

What is MATLAB? MATrix LABoratory


Provides a technical computing environment designed to
support the implementation of computational tasks

numerical computations
scientific visualization
symbolic computations

Both a computer programming language and a software


environment for using that language effectively
Designed by Cleve Moler in 1970s as a teaching tool and
to make matrix computations particularly easy to perform
Interprets commands entered and executed by a user

Users type commands and receive answers immediately (very


useful for solving simple problems)
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

What is MATLAB? MATrix LABoratory (contd)


Characteristics of MATLAB

Automatic memory management


Intuitive and easy to use
Includes many specialized capabilities (called Toolboxes)
Ubiquitous in industry and education
Relatively slow (as compared to other languages)

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Starting MATLAB & MATLAB Windows


Launching MATLAB

Start All Programs MATLAB

The MATLAB interface comprises a collection of windows

Command Window
Workspace Window
Current Folder Window
Editor Window
Figure Window
Help Window

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Working in the Command Window


You can interact with MATLAB in one of two modes

Interactive mode or Batch mode

Interactive mode

User types commands directly into the command window


Basic procedure for working with the command window in
interactive mode
1.
2.
3.
4.

At prompt (>>), type in a MATLAB command


Press ENTER key
MATLAB displays result in Command Window, followed by
displaying the prompt (>>) again
Repeat step 1

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Working in the Command Window (contd)


Notes on Command Window

To start a command, make sure cursor is next to prompt (>>)


MATLAB wont execute the command until you press ENTER
It then executes only last command
Commands before last one may still be visible, but MATLAB
doesnt execute them
If command too long to fit on line, can continue to next line by
typing ellipsis (3 periods, i.e., ) and then pressing ENTER

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Working in the Command Window (contd)

Notes on Command Window (contd)

When cursor is in bottom command line:

10

key moves cursor one character to left


key moves cursor one character to right
key recalls preceding command
key opposite functionality of key

PAGE-UP key moves up to previous commands in a window-size


at a time
PAGE-DOWN key moves down to most recently executed
commands in a window-size at a time
BACKSPACE key deletes character to left of cursor
DELETE key deletes character to right of cursor
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Working in the Command Window (contd)

Semicolon (;)

When typed at end of a command, suppresses output. (Only


prompt displayed at next line)
Useful for preventing display of large outputs
Used much more in scripts (much more on this later)

Percent sign ( % )

11

When typed at beginning of line, MATLAB treats line as a


comment and doesnt execute line
Used much more in scripts

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Working in the Command Window (contd)

clc Command Clear Command/Console Window


Up and down arrows still bring back previous commands,
Cannot use scroll bar to view history of executed commands
help Command Access MATLABs documentation
>>help
>>help command_name

doc Command Launch/open Documentation Browser


>>doc
>>doc command_name

edit Command Launch/open Editor Window


>>edit
>>edit file_name
quit Command Exit/close MATLAB
>> quit
12

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

A Type of Quantity: Scalar

Scalar a single numerical quantity (can be negative)


For now, we will restrict our discussion to scalar arithmetic
MATLAB number representations and formats

13

Integers: 1362, 217897


Reals:
123.82, 110.3449, 1.23e14, -12.456e-15
Complex: 8 + 3, 10.34 25.88

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Scalars: Arithmetic Operators and Operations

Some arithmetic operators for scalars include

Subtraction:
Exponentiation:
Left Division (Reciprocal): \

Order of Precedence
1.
2.
3.

4.

Addition: +
Multiplication: *
Right Division: /

Parenthesis (evaluated from innermost to outermost)


Exponentiation
Multiplication and Division (evaluated from left to right)
Addition and Subtraction (evaluated from left to right)

Notes on Order of Precedence

14

For multiple operations of same precedence, MATLAB evaluates


the operations from left to right
Can change order by using parenthesis
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Using MATLAB as a Calculator

Can use MATLAB as a (very expensive!) calculator

At the prompt (>>), type in mathematical expression


Press Enter key
MATLAB displays answer in Command Window as ans =
followed by the result

Show Examples

15

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Using MATLAB as a Calculator (contd)

A function is a kind-of black box that performs a


computation on inputs and generates outputs
Function
Name
Inputs

has a name (associated with type of computation)


accepts zero or more inputs (arguments)

Outputs

can be numbers, variables (explained later), or even expressions


involving numbers, variables, or functions

returns zero or more outputs (results)

Example

y = sqrt( x )
output name argument

16

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

MATLAB Built-In Functions

Elementary Math Functions (See Table 1.3 for details)

sqrt(x) square root


nthroot(x,n) nth real root = 1

17

Can also be done using a combination of the exponentiation and


right division operators

exp(x) Exponential
abs(x) Absolute value
log(x) natural (base ) logarithm = log ()
log10(x) base-10 logarithm log10
factorial(n) ! = 1 2 3 3 2 1

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

MATLAB Built-In Functions

Trig. Functions (use MATLAB help for details)

18

sin(x) sine ( in radians)


sind(x) sine ( in degrees)
cos(x) cosine ( in radians)
cosd(x) cosine ( in degrees)
tan(x) tangent ( in radians)
tand(x) tangent ( in degrees)
cot(x) cotangent ( in radians)
cotd(x) cotangent ( in degrees)

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

MATLAB Built-In Functions

Inverse Trig. Functions (use MATLAB help for details)

19

asin(x) inverse sine ( in radians)


asind(x) inverse sine ( in degrees)
acos(x) inverse cosine ( in radians)
acosd(x) inverse cosine ( in degrees)
atan(x) inverse tangent ( in radians)
atand(x) inverse tangent ( in degrees)
acot(x) inverse cotangent ( in radians)
acotd(x) inverse cotangent ( in degrees)

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

MATLAB Built-In Functions

Rounding Functions (use MATLAB help for details)

20

round(x) round to nearest integer


fix(x) round toward zero
ceil(x) round toward infinity
floor(x) round toward minus infinity
rem(x, y) remainder of
What is the difference??
mod(x, y) remainder of
find out with MATLAB help!
sign(x) returns +1 if > 0,
returns 1 if < 0,
returns 0 if = 0

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Variables and Assignment Operator

Variable: Name (identifier) of a memory location that


can be assigned a numerical value

Define a variable by assigning a value to it for the first time


Once defined, can be used in expressions, functions, and
MATLAB statements and commands
Once defined, can read from the variable (get its value) and
write to the variable (set/assign its value)

Cannot use a variable before you define it!

Assignment operator (=): Assigns value to defined


variable

21

Evaluates expression on right hand side (RHS) and stores the


resulting value in the variable on left hand side (LHS)
variable_name = expressions
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Variables and Assignment Operator (contd)

Notes on the Assignment Operator

Think about the meaning of the statement x = x + 6

= means assign to or store in


Does not mean equal to like it does in math notation!
Has no meaning in math because it implies that 0 = 6
Perfectly fine in MATLAB because it means read value stored in
x, add 6 to it, and store the result back to x

Example

22

>> x = 3;
>> x = x + 6; %read value stored in x,
%add 6 to it,
%and store result back in x
>> x = 2 * x; %read value stored in x,
%double it,
%and store result in x
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Naming Variables

MATLAB has rules for naming variables


Names must begin with a LETTER and may be followed by any
combination of letters, digits, and underscores ( _ )
Names are case sensitive (NAME, name, Name are distinct)
Names cannot contain punctuation or spaces, e.g., (. , ; - )
Names cannot be longer than 63 characters
Cannot name a variable the same as a MATLAB keyword
Avoid using the name of a built-in function as the name of a variable,
e.g., dont call a variable exp or sqrt
iskeyword Command
Lists MATLAB keywords
exist Command
Checks if supplied function name exists
Returns positive number if found, zero otherwise

23

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Naming Variables (contd)

Always choose meaningful names when defining variables.


Sometimes, this means choosing long/descriptive names

Some naming conventions that programmers use which


avoid spaces and yet abide by MATLABs naming rules
Convention #1: Use underscores instead of spaces to
separate every word of a variable name

Remember, names cannot contain punctuation or spaces

Example: speed_of_light

Convention #2: Utilize camel case naming method.


Capitalize first letter of every word except first word in the
name of a variable

24

Example: speedOfLight
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Predefined MATLAB Variables

Commonly used scalars in MATALB have been given


predetermined variable names (identifiers)

ans the value of the previous calculation that was not assigned to a
variable
pi The number 3.14159
eps Smallest difference between two real numbers capable of
being represented by MATLAB and the associated computer on which
MATLAB is installed

25

The value of eps is 2.2204 x 10-16

inf or Inf Infinity ( )


i Defined as 1 = = 0 + 1
j Same as 1 = . Commonly used by electrical engineers
instead of
NaN or nan Not A Number. Used to express mathematically
undefined values, such 0/0
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Predefined MATLAB Variables (contd)

(Caution) Redefining Predefined Variables

One may redefine (change) values of the predefined variables


Generally, not a good idea! You may confuse yourself and/or
others!
Sometimes however, you may inevitably redefine a few
predefined variables without possibly realizing it!

Example
>>i
ans =
0.0000 + 1.0000i
>>i = 20.5
%redefine predefined value of i
i =
20.5000
26

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

String Variables and Displaying Messages

So far, we have only stored scalars (numbers) in variables.


We can also store character strings in variables
Character String A list of characters in MATLAB that can
be stored in a variable

The list of characters is surrounded by single quotes


Useful for displaying information, labeling output, and passing
the names of M-files as arguments (inputs) to functions

Examples
>>ENGR 15100 is easy!
>> myName = Steve Naumov;
>> aSingleSpace = ;
27

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

String Variables and Displaying Messages (contd)

disp(var) function Display value stored in variable var in the


Command Window without displaying the actual name of the
variable

Restrict ourselves to scalar and string variables (for now)

Example
>> temp = 90; %why didnt MATLAB display the result
>> disp(temp)
90
>> disp(Today is a hot day!);
Today is a hot day!
>> myName = Steve Naumov;
>> disp(myName)
Steve Naumov

28

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Saving Interactive MATLAB Sessions

Log a list of commands entered in the Command Window


diary Command Saves text of interactive session to a file

Causes copy of all subsequent commands entered in command


window and resulting output to be appended to a ASCII text file

Examples

29

diary - creates a diary file named diary in the current working


directory (folder) (assumes a diary has not previously been created)
diary FILENAME.txt Creates a diary file named
FILENAME.txt in the current working directory (folder)
diary OFF or off suspends logging of interactive session
diary ON or on resumes logging of interactive session
diary toggles diary state (assumes diary has been created
previously)
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Managing Variables and Workspace

clear Command Clears all (selected) variables in the


MATLAB workspace by removing all (selected) currently
defined variables from memory
Examples

>> clear all Removes all currently defined variables


from workspace
>> clear var1 var2 Removes only variables var1 and
var2 currently defined in workspace

who or whos Command Displays all currently defined


variables in workspace. whos also displays variable sizes
and other information
30

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Managing Variables and Workspace (contd)

save Command Saves all (selected) defined variables in


workspace of interactive session to binary MAT-file
Examples

31

>> save - saves all variables currently defined in workspace


to a MAT-file named matlab.mat. MAT-file created in
current directory (folder)
>> save FILENAME.mat saves all variables currently
defined in workspace to a MAT-file named FILENAME.mat.
MAT-file created in current directory (folder)
>> save FILENAME.mat var1 var2 saves variables
var1 and var2 currently defined in workspace to a MAT-file
named FILENAME.mat. MAT-file created in current directory
(folder)
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Managing Variables and Workspace (contd)

load Command Loads data (variables) saved in a MATfile from disk back into workspace of interactive session
Examples

32

>> load loads all data (variables) saved in a MAT-file named


matlab.mat. Assumes MAT-file resides in current directory
(folder)
>> load FILENAME.mat loads all data (variables) stored
in a MAT-file named FILENAME.mat. Assumes MAT-file
resides in current directory (folder)
>> load FILENAME.mat var1 var2 loads only variables
var1 and var2 stored in a MAT-file named FILENAME.mat.
Assumes MAT-file resides in current directory (folder)
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Batch Mode Interaction w/ MATLAB

You can interact with MATLAB in one of two modes

Interactive mode or Batch mode

Batch mode

33

A series of commands are typed in a special text file


The commands in the file can then be executed by MATLAB
Advantage is that it is easier to make small changes to the
commands in the file without having to remember or retype all
the commands from scratch

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Script Files

Script File File containing a sequence of MATLAB


commands

34

When a script file runs (is executed), MATLAB performs the


commands in the order they are written, just as if they were
typed in the Command Window in the same sequence.
When a script file has a command that generates an output
(e.g. assignment of a value to a variable without semicolon at
the end), MATLAB displays the output in the Command Window
Using a script file is convenient because it can be edited
(corrected and/or changed) and executed many times
Script files can be typed and edited in any text editor and then
pasted into the MATLAB editor
Script files are also called M-files because the extension .m is
used when they are saved
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Creating, Saving, and Executing M-Files

Different way to create Scripts in MATLAB user interface

Creating scripts in the Command Window using the edit


Command

Click the New Script button in the Home tab


Click arrow of New button in the Home tab and select Script

>>edit Launches the Editor Window


>>edit FILENAME.m Launches Editor Window and opens
M-file named FILENAME.m. Assumes FILENAME.m resides
in current directory (folder). If not, MATLAB may ask you if you
want to create the file in current directory (folder)

Examples/Demos
35

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Creating, Saving, and Executing M-Files (contd)

Before executing commands in an M-file, save it!

If youve already named and saved the M-file, just click on the
Save button in the Editor tab
If you havent named the M-file yet, click the arrow on the Save
button in the Editor tab, then choose Save As

Naming rules for files are similar to rules for variable names

36

Type in a name in the dialog box. If you dont add a .m extension to


the file name, MATLAB adds .m for you
Then click Save button
Dont use names of your variables, predefined variables, MATLAB
commands, or MATLAB functions

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Creating, Saving, and Executing M-Files (contd)

To execute a script file means to execute all commands


contained within the M-file
Ways to execute M-files using Editor Window

Press the Run button in the Editor Tab


Press the arrow of the Run button in the Editor tab and select
the script name you wish to execute

Ways to execute M-files using Command Window

37

Type the M-file name in Command Window and press ENTER


MATLAB will execute file if the file resides in current directory
(folder)
If not, you can change current directory (folder) with buttons
above the Current Folder Window
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Errors in Scripts/Programs

Script errors manifest themselves after the user asks MATLAB


to execute the script
Script errors can fall into one of the following categories

Syntax errors such as omitting a parenthesis or comma, or spelling a


command name incorrectly

MATLAB usually detects the more obvious errors and displays a message
describing the error and its location

MATLAB ALSO halts the execution of the script at the point of the error

Runtime errors due to an incorrect mathematical procedure

Logical errors that result in an incorrectly functioning script/program

38

Their occurrence often depends on the particular input data


Example: Division by zero

Example 1: Incorrectly calculating the area of a circle


Example 2: Inadvertently using + operator instead of * operator
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Locating and Correcting Errors in Scripts

Locating errors in programs

Test script with simple solution which is easily checked by hand


Display any intermediate calculation at different points in the script

Ask for help if you are spinning your wheels

Remove semicolons at the end of statements


Use the disp() function to display values stored in variables
Talk to a friend
Contact the Teaching Assistant
Contact the Instructor

Correcting errors in programs is called debugging

39

Edit the script file to try to correct the error


Re-save and re-execute the script
If the error persists or a new error arises or is reported by MATLAB,
repeat the above steps
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Example Problem

Create a new script named LASTNAME_example1.m and


solve the following problem by typing commands in the
script file you created

In the circular cylinder shown to the


right, radius = 22.4 and height

= 15.9

Determine the following:

40

Circumference and area of the circular


surface in and 2
Perimeter and area of the rectangular
surface in and 2
Surface area, , of entire circular cylinder in 2

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Example Solution
%--------------------------------------------------------------------------------% Author: Steve Naumov
% Filename: example.m
% Purpose: This file computes circumference/area of a circle, perimeter/area
% of a rectangle, and uses those results to compute the surface area of a cylinder
%--------------------------------------------------------------------------------radius_in_mm = 22.4;
%suppress display in command window
height_in_cm = 15.9;

%---------------------------------------------------------------% calculate radius in centimeters


%---------------------------------------------------------------radius_in_cm = radius_in_mm * (1/10);
%conversion factor 1cm = 10mm
%---------------------------------------------------------------% calculate circumference and area of circle C in cm and cm^2
%---------------------------------------------------------------circumference_in_cm = 2 * pi * radius_in_cm;
area_of_circle_in_cm2 = pi * (radius_in_cm^2);

%---------------------------------------------------------------% Display results for circle C


%---------------------------------------------------------------disp('-----------------------------------------------------------');
disp('The circumference and area of circle C in cm and cm^2 is: ');
disp('-----------------------------------------------------------');
circumference_in_cm
area_of_circle_in_cm2

41

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Example Solution (contd)


%---------------------------------------------------------------% calculate perimeter and area of rectangle R in cm and cm^2
%---------------------------------------------------------------perimeter_in_cm = 2*height_in_cm + 2*circumference_in_cm;
area_of_rectangle_in_cm2 = height_in_cm * circumference_in_cm;

%---------------------------------------------------------------% Display results for rectangle R


%---------------------------------------------------------------disp('-----------------------------------------------------------');
disp('The perimeter and area of rectangle R in cm and cm^2 is: ');
disp('-----------------------------------------------------------');
perimeter_in_cm
area_of_rectangle_in_cm2

%---------------------------------------------------------------% calculate surface area of circular cylinder


%---------------------------------------------------------------surface_area_in_cm2 = area_of_rectangle_in_cm2 + 2*area_of_circle_in_cm2;

%---------------------------------------------------------------% Display results for circular cylinder


%---------------------------------------------------------------disp('-----------------------------------------------------------');
disp('The surface area, S, of circular cylinder in cm^2 is: ');
disp('-----------------------------------------------------------');
surface_area_in_cm2

42

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Lecture Summary

This set of lecture notes described:

43

What is computer programming


What is MATLAB
Starting MATLAB and MATLABs User Interface
Working with MATLABs Command Window
Arithmetic Operations with Scalars
Elementary Built-in Functions
Defining Scalar & String Variables
Managing Variables
Script Files
Errors in Script Files
ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM