2 views

Uploaded by Atindriya

Matlab

- Printing on fortran 77
- 1109.4436
- chapter_01_Drill_solution_by_Hayt_7th_8t.pdf
- Problem Set 1
- Class12 Mathematics1 Unit02 NCERT TextBook EnglishEdition
- Final Curriculum ME
- 1 Example - Airfoil Forces Calculation - Analytical
- math_h.pdf
- The Derivative English
- Trigonometry (11th Edition) (2016)
- Student Note - Differentiation Techniques
- Guia Estudio Mendel
- bpj lesson 6
- 0111ExamA2
- Ksp
- AQA Core 3 Revision Notes
- Integration Techniques
- Question Bank 0606 (1)
- text 1b em
- Syllabus

You are on page 1of 43

ENGR 15100: Software Tools for Engineers

Steve Naumov (Instructor)

Lecture Overview

This set of lecture notes describes:

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?

designed to be executed by a machine, particularly a computer

particular order dictating computations to be performed

unit (CPU or brain) of a computer

Example:

+1300042774

+1400593419

+1200274027

1/10/2017 10:54:05 AM

Broad Categories of Computer Languages

elementary computer operations. Translated to machine

language with assemblers

Example:

LOAD BASEPAY

ADD OVERPAY

STORE GROSSPAY

English by utilizing notation similar to mathematical notation.

Translated to assembly/machine language with compilers

Example:

grossPay = basePay + overTimePay;

circle_area = pi * radius * radius;

1/10/2017 10:54:05 AM

Provides a technical computing environment designed to

support the implementation of computational tasks

numerical computations

scientific visualization

symbolic computations

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

useful for solving simple problems)

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Characteristics of MATLAB

Intuitive and easy to use

Includes many specialized capabilities (called Toolboxes)

Ubiquitous in industry and education

Relatively slow (as compared to other languages)

1/10/2017 10:54:05 AM

Launching MATLAB

Command Window

Workspace Window

Current Folder Window

Editor Window

Figure Window

Help Window

1/10/2017 10:54:05 AM

You can interact with MATLAB in one of two modes

Interactive mode

Basic procedure for working with the command window in

interactive mode

1.

2.

3.

4.

Press ENTER key

MATLAB displays result in Command Window, followed by

displaying the prompt (>>) again

Repeat step 1

1/10/2017 10:54:05 AM

Notes on Command Window

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

1/10/2017 10:54:05 AM

10

key moves cursor one character to right

key recalls preceding command

key opposite functionality of key

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

Semicolon (;)

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

comment and doesnt execute line

Used much more in scripts

1/10/2017 10:54:05 AM

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

>>doc command_name

>>edit

>>edit file_name

quit Command Exit/close MATLAB

>> quit

12

1/10/2017 10:54:05 AM

For now, we will restrict our discussion to scalar arithmetic

MATLAB number representations and formats

13

Reals:

123.82, 110.3449, 1.23e14, -12.456e-15

Complex: 8 + 3, 10.34 25.88

1/10/2017 10:54:05 AM

Subtraction:

Exponentiation:

Left Division (Reciprocal): \

Order of Precedence

1.

2.

3.

4.

Addition: +

Multiplication: *

Right Division: /

Exponentiation

Multiplication and Division (evaluated from left to right)

Addition and Subtraction (evaluated from left to right)

14

the operations from left to right

Can change order by using parenthesis

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Press Enter key

MATLAB displays answer in Command Window as ans =

followed by the result

Show Examples

15

1/10/2017 10:54:05 AM

computation on inputs and generates outputs

Function

Name

Inputs

accepts zero or more inputs (arguments)

Outputs

involving numbers, variables, or functions

Example

y = sqrt( x )

output name argument

16

1/10/2017 10:54:05 AM

nthroot(x,n) nth real root = 1

17

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

1/10/2017 10:54:05 AM

18

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)

1/10/2017 10:54:05 AM

19

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)

1/10/2017 10:54:05 AM

20

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

1/10/2017 10:54:05 AM

can be assigned a numerical value

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)

variable

21

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

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

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

1/10/2017 10:54:05 AM

Sometimes, this means choosing long/descriptive names

avoid spaces and yet abide by MATLABs naming rules

Convention #1: Use underscores instead of spaces to

separate every word of a variable name

Example: speed_of_light

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

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

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

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

1/10/2017 10:54:05 AM

We can also store character strings in variables

Character String A list of characters in MATLAB that can

be stored in a variable

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

1/10/2017 10:54:05 AM

Command Window without displaying the actual name of the

variable

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

1/10/2017 10:54:05 AM

diary Command Saves text of interactive session to a file

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

Examples

29

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

MATLAB workspace by removing all (selected) currently

defined variables from memory

Examples

from workspace

>> clear var1 var2 Removes only variables var1 and

var2 currently defined in workspace

variables in workspace. whos also displays variable sizes

and other information

30

1/10/2017 10:54:05 AM

workspace of interactive session to binary MAT-file

Examples

31

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

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

Examples

32

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

33

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

1/10/2017 10:54:05 AM

Script Files

commands

34

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

Command

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

>>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

1/10/2017 10:54:05 AM

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

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

1/10/2017 10:54:05 AM

contained within the M-file

Ways to execute M-files using Editor Window

Press the arrow of the Run button in the Editor tab and select

the script name you wish to execute

37

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

to execute the script

Script errors can fall into one of the following categories

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

38

Example: Division by zero

Example 2: Inadvertently using + operator instead of * operator

ENGR 15100 (Lecture #1), Naumov

1/10/2017 10:54:05 AM

Display any intermediate calculation at different points in the script

Use the disp() function to display values stored in variables

Talk to a friend

Contact the Teaching Assistant

Contact the Instructor

39

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

solve the following problem by typing commands in the

script file you created

right, radius = 22.4 and height

= 15.9

40

surface in and 2

Perimeter and area of the rectangular

surface in and 2

Surface area, , of entire circular cylinder in 2

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;

%---------------------------------------------------------------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);

%---------------------------------------------------------------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

1/10/2017 10:54:05 AM

%---------------------------------------------------------------% 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;

%---------------------------------------------------------------disp('-----------------------------------------------------------');

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

disp('-----------------------------------------------------------');

perimeter_in_cm

area_of_rectangle_in_cm2

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

%---------------------------------------------------------------disp('-----------------------------------------------------------');

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

disp('-----------------------------------------------------------');

surface_area_in_cm2

42

1/10/2017 10:54:05 AM

Lecture Summary

43

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

- Printing on fortran 77Uploaded byAhmed Siddique
- 1109.4436Uploaded byTuring Daniela
- chapter_01_Drill_solution_by_Hayt_7th_8t.pdfUploaded byNoor Ul Ain
- Problem Set 1Uploaded bybob
- Class12 Mathematics1 Unit02 NCERT TextBook EnglishEditionUploaded byUdit Chaudhary
- Final Curriculum MEUploaded byRohitkumar Rathod
- 1 Example - Airfoil Forces Calculation - AnalyticalUploaded bybatmanbittu
- math_h.pdfUploaded byRandy Smith
- The Derivative EnglishUploaded byAlfia Magfira
- Trigonometry (11th Edition) (2016)Uploaded byMatei Marian
- Student Note - Differentiation TechniquesUploaded bypirawin92
- Guia Estudio MendelUploaded byEdward Eceinco
- bpj lesson 6Uploaded byapi-307093682
- 0111ExamA2Uploaded byCarla Coelho
- KspUploaded bydrummergood1978
- AQA Core 3 Revision NotesUploaded byzordman1
- Integration TechniquesUploaded bySalvadora1
- Question Bank 0606 (1)Uploaded byAzratee Zawawi
- text 1b emUploaded bykrish
- SyllabusUploaded byAnil Shah
- eighth grade key learningsUploaded byapi-344851377
- Mock Test 4 - AnswersUploaded byMAT_Notes
- Power System Faults Phase Selection Project-4Uploaded byIndrajeet Prasad
- CBSE ClassXI SamplePaper1Uploaded byEsme Ruthbell
- Mathematics 9709Uploaded byJohn Nathan Henry
- GS34M06A01-01E_015.pdfUploaded bymarklmendoza
- Territorial Army Notification 2019 SSBCrackUploaded byHarsh Jasrotia
- 487B.pdfUploaded byThien Doanh
- CBSE Class 11 Mathematics Question Paper SA1 2012 (1)Uploaded byabhishekaks97
- Introduction to DerivativesUploaded byvanamgoutham

- Mainframe - Parte 7 - Apostila CICSUploaded byCsoluz Infinity
- MIcrocontroller 8051 Theory and Interfacing.pdfUploaded byjohn
- spru357bUploaded bysudhaa206
- EEE_3506_EXP8Uploaded byAshik iqbal
- optimisation of embeded compilersUploaded byMani Bharath Nuti
- Examination Result Automation for Secondary Schools MainUploaded byIbe Collins
- SS Macro ProcessorUploaded byingaleabhijeet2010
- Computer ionUploaded byVikram Rao
- Instruction Objectives of Each ChapterUploaded byahmedmalek
- CRTLUploaded bybabybin2100
- man_1_gccUploaded byabrfrkuy
- Micro PossessorUploaded bynawaz dar12
- cs2100-10-MIPSUploaded byamanda
- BE_CS_II-IVYearUploaded bysahilpahuja01
- Microprocessor Lesson PlanUploaded byKavitha Subramaniam
- 8085 NotesUploaded byDavid Talam
- Machine Language for the Commodore 64Uploaded byMaxim Šporki
- MICROPROCESSOR NOTES.docxUploaded byeidermutum
- Mpmc Lab Manual_ AlietUploaded byAkbarSab
- Microcontrollers_Lab Manual_Final.docxUploaded byPrince Raj
- CS-64Uploaded byShekhar Rawat
- 03 Chapter 4 - Starting to ProgramUploaded bysvhanu4010
- ICE SyllabusUploaded byadsharif
- Coa Experimentno.3(Output)Uploaded byGlennNacarGan
- 8051 Micro ControllerUploaded byKumar Rathore
- TY-BSc-Computer-Science_25-06-15.pdfUploaded byAfreen Bhumgara
- First Steps with Embedded SystemsUploaded byapi-3783901
- Lab 10Uploaded bysanjay1702
- Assebly Lab PrintUploaded byPRATIK_DARBHE
- 351 Microprocessor (1)Uploaded bySupreeti Gupta