introduction to matlab

60
CS101 – Computer Systems 1 © Chathura De Silva, Dept. of Computer Science and Engineering CS-101: Computer Systems Introduction to programming using MatLab Lecture 1

Upload: nicksolden

Post on 05-May-2017

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to matlab

CS101 – Computer Systems 1© Chathura De Silva, Dept. of Computer Science and Engineering

CS-101: Computer Systems

Introduction to programming using MatLab

Lecture 1

Page 2: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 2© Chathura De Silva, Dept. of Computer Science and Engineering

Page 3: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 3© Chathura De Silva, Dept. of Computer Science and Engineering

Introduction to MATLAB

What is MATLAB?

n Short for MATrix LABoratory

n Capable of solving any technical problems

n A Special-purpose, interpreter-based, computer application for technical computing, simulation, engineering and scientific computing, numerical computation and visualization.

n May be used without intensive programming knowledge.

n MATLAB computing environment – Widely used for scientific and engineering.

n Developed and marketed by a company called MathWorks(http://www.mathworks.com).

Page 4: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 4© Chathura De Silva, Dept. of Computer Science and Engineering

Introduction to MATLAB (continue)

The Advantage of MATLABn Ease of Use n Platform Independencen A large collection of predefined functions

n Arranged into “toolboxes” for different deciplines.n Device-Independent Plottingn Graphical User Interfacen MATLAB Compiler

Disadvantages of MATLABn Interpreted language – slown Costn Not for symbolic manipulations

Page 5: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 5© Chathura De Silva, Dept. of Computer Science and Engineering

Introduction to MATLAB (continue)

The MATLAB Environment includes

n Graphical user interfacen MATLAB desktop and Command Windown A command historyn An editor and debugger, and n A Browser for viewing help, the workspace, files, and

the search path.

Page 6: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 6© Chathura De Silva, Dept. of Computer Science and Engineering

Introduction to MATLAB (continue)

n MATLAB Desktop – the main interface for working with MATLAB

Page 7: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 7© Chathura De Silva, Dept. of Computer Science and Engineering

Introduction to MATLAB (continue)

n MatLab could be used in two different modesn Command Mode (Interactive Mode)

n Similar to a scientific calculator (but with lot more features).

n Input a single operation (i.e. mathematical expression) and results are displayed immediately.

n Programmed Mode (Scripting Mode)n Like a programmable calculator (but can

accommodate very large programs).n Define sequences of operations involving

variables and functions.

Page 8: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 8© Chathura De Silva, Dept. of Computer Science and Engineering

MATLAB Electrical Calculator:An Interactive Session

n Start MATLABn Example1: Enter the

following lines on the MATLAB Command Windows

>> watt = 100;>> volt = 220;>> i = watt/volti =

0.4545n Double Click the Command

in the Command History Window

Workspace

Command Window

Command History

Page 9: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 9© Chathura De Silva, Dept. of Computer Science and Engineering

MATLAB Electrical Calculator:an Interactive Session (continue)

n Example 2: Calculate the area of a circle with a radius of 0.001 inch (p r2).

>> pians =

3.1416>> area = pi*0.001^2area =

3.1416e-006

>>

Page 10: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 10© Chathura De Silva, Dept. of Computer Science and Engineering

MATLAB: an Interactive Session

n Example 3: Sum of 12 numbers with continue statement on successive lines by typing an ellipsis (…) at the end of the first line

>> x = 1 + 2+3+4+5+6+7+8+9+10+11+12x =

78

>> x = 1 + 2 + 3 + 4 + ...5 + 6 + 7 + 8 + 9 + 10 + 11 + 12x =

78

Page 11: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 11© Chathura De Silva, Dept. of Computer Science and Engineering

Using Constants and Variables

n Like in algebra, we can use symbols (i.e. Identifiersor Variables) to represent unknown quantities.

22 3 5y x x= + +

n Result of the expression (i.e. value assigned to variable ‘y’) depends on the value of ‘x’.

n On symbolic arithmetic point of view, y can be defined in terms of ‘x’. However on numerical terms, without a value assigned for ‘x’, ‘y’ remains undefined.

n In MatLab, an expression can be evaluated only if all variables in the right-hand side are assigned with values.

Page 12: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 12© Chathura De Silva, Dept. of Computer Science and Engineering

Using Constants and Variables

n Constants: sum of resistance (ohms)n 100 + 120

n Variables: sum of resistancen R1 + R2 + 0.01

Page 13: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 13© Chathura De Silva, Dept. of Computer Science and Engineering

Constants and Variables (cont.)

n MATLAB Sum Calculator: enter the following lines at the MATLAB command window:

>> 100 + 120 ans = 220>> Rt = 100 + 120Rt = 220

>> R1 = 100;>> R2 = 120;>> R1 + R2 + 0.01ans = 220.01

Page 14: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 14© Chathura De Silva, Dept. of Computer Science and Engineering

Constants and Variables (cont.)

MATLAB Variables and Assignmentsn No need to declare MATLAB variables before they are used.

Assigns a value to a variable creates the variable.n Variable names must begin with a letter, which may be

followed by any combination of letters, digits, and underscores.

n Case Sensitive, so A and a are not the same variable.n The variable on the right-hand side of the assignment must

has a value.n A variable’s value is over written if it already exists.

Page 15: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 15© Chathura De Silva, Dept. of Computer Science and Engineering

Constants and Variables in MatLab

n As the name implies (MATrix LABoratory), MatLabtreats each and every variable as a “Matrix”.

n Thus scalar values are treated as special case matrices, a 1x1 dimension matrix.

n Constants are also like variables, except their values will never change.

n There are some pre-defined constants which cannot be changed.

Page 16: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 16© Chathura De Silva, Dept. of Computer Science and Engineering

Constants and Variables (cont.)

n Natural Numbers: counting numbers) =

{1, 2, 3, 4, 5, 6, …} (will go till infinity, but practical sequences will always have a limit)

n In MatLab a number sequence can be represented as follows

<start>:<step_size>:<end>

n MATLAB row vector commands

>> x = 1: 1: 10

or

>> x = 1:10

Page 17: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 17© Chathura De Silva, Dept. of Computer Science and Engineering

Constants and Variables (cont.)

n Whole Numbers: {0, 1, 2, 3, 4, 5, 6, …}n Add 0 to the whole numbersn MATLAB Commands>> x = [0, x]or

>> clear x>> x = 0:1:10

Page 18: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 18© Chathura De Silva, Dept. of Computer Science and Engineering

Constants and Variables (cont.)

n Integers: {…, -3, -2, -1, 0, 1, 2, 3, …}

n Combining wholenumbers andnegatives of thewhole numbers

n MATLAB Commands>> y = -3:3y =

-3 -2 -1 0 1 2 3

Page 19: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 19© Chathura De Silva, Dept. of Computer Science and Engineering

Constants and Variables (cont.)

n Some Predefined MATLAB Variables

n ans – holds the value of the most recent calculation result

n pi – p(Circumference/Diameter), ratio of the circumference of a circle to its diameter; pi = 3.1415926 …

n eps - Smallest number such that when added to 1 create a floating-point number greater than 1; eps = 2.2204e-016.

n inf - Positive infinity, generated through divided by zero, such as 1/0

Page 20: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 20© Chathura De Silva, Dept. of Computer Science and Engineering

( ) ( )( )

2 2 2 2

21 2

x x x x

x x x x x x x

x x

− = −

− = − +

==

Page 21: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 21© Chathura De Silva, Dept. of Computer Science and Engineering

Constants and Variables (cont.)

n Some Predefined MATLAB Variables

n NaN - Not a number, obtained from invalid operations such as 0/0, inf/inf, and so on.

n realmax - Largest positive floating point number; realmax = 2.2251e308.

n realmin - Smallest positive floating point number; realmin = 2.2251e-308.

Page 22: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 22© Chathura De Silva, Dept. of Computer Science and Engineering

Constants and Variables (cont.)

n Some Prefixes for SI Units (International Standard)

µmicro10-6

nnano10-9

ppico10-12

ffemto10-15

aatto10-18

zzepto10-21

yyocto10-24

Abbreviation

PrefixPower

Page 23: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 23© Chathura De Silva, Dept. of Computer Science and Engineering

Constants and Variables

n Some Prefixes for SI Units (International Standard)

Ggiga109

Mmega106

kkilo103

dadeka101

ddeci10-1

ccenti10-2

mmilli10-3

Abbreviation

PrefixPower

Source: http://www.frontierusa.com/

Page 24: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 24© Chathura De Silva, Dept. of Computer Science and Engineering

Constants and Variables

n Some Prefixes for SI Units (International Standard)

YYotta1024

ZZetta1021

Eexa1018

Ppeta1015

Ttera1012

AbbreviationPrefixPower

Page 25: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 25© Chathura De Silva, Dept. of Computer Science and Engineering

MATLAB Math. Operators

Operators

+ op1 + op2 Adds op1 and op2

- op1 – op2 Subtract op2 from op1

* op1 * op2 Multiplies op1 by op2

/ op1 / op2 Divide op1 by op2

^ op1 ^ op2 Computes the power op1 goes to the power of op2

Page 26: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 26© Chathura De Silva, Dept. of Computer Science and Engineering

MATLAB Math. Operators (cont.)

n Arithmetic Expressions

n velocity = distance / time;

n force = mass * acceleration;

n count = count + 1;

n power = V^2/R;

Page 27: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 27© Chathura De Silva, Dept. of Computer Science and Engineering

MATLAB Math. Operators

n Example 2-1: Mr. A rides a bike 140 meters in 20 second. What is the average speed of bike riding?

n MATLAB Solution>> v = 140/20v =

7

Page 28: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 28© Chathura De Silva, Dept. of Computer Science and Engineering

MATLAB Math. Operators (cont.)

n Example 2-2: Neglecting friction and air resistance, what force is required to accelerate an automobile weighting 2000 lbs from 30.0 miles/hr to 55.0 miles/hr in 10.0 second.

MATLAB Solution>>% acceleration a = vf – v1/ dt

% force = ma (comments)>> m = 2000;>> a = (55.0 - 30.0)/(10/3600);>> f = m*af =

18000000

Page 29: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 29© Chathura De Silva, Dept. of Computer Science and Engineering

MATLAB Math. Operators (cont.)

n Example 2-3: Electric Power Calculation, for R = 15 ohms, voltage = 120 volts: P = V^2 /R (watts).

MATLAB Solution:

>>R = 15.0;>>V = 120;>>P = V^2 / RP =

960

Page 30: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 30© Chathura De Silva, Dept. of Computer Science and Engineering

Writing and Evaluating Math.Equations in MATLAB Operators (cont.)

Example 2-4: The sum of three consecutive numbers is 93. Find the numbers.

Solution:Step 1: Represent unknown quantities as variables

Let x be the consecutive numberLet x + 1 be the second consecutive number Let x + 2 be the third consecutive number

Step 2: Write the equationx + (x + 1) + (x + 2) = 93

Step 3: Solve x3x + 3 = 933x = 90x = 30

Page 31: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 31© Chathura De Silva, Dept. of Computer Science and Engineering

Writing and Evaluating Math.Equations in MATLAB Operators (cont.)

Example 2-4: The sum of three consecutive numbers is 93. Find the numbers.

Solution:

Step 4; Using the equation in Step 2 and MATLAB command to verify the answer.

>> x = 30;>> x + (x +1) + (x +2)>> ans

= 93

Page 32: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 32© Chathura De Silva, Dept. of Computer Science and Engineering

Writing and Evaluating Math.Equations in MATLAB Operators (cont.)

Example 2-5: There are two ICs on a circuit board, one called IC1 and another called IC2. There is an average operating temperature of 65ºC. What is the operating temperature of each IC if the IC2 has a 10ºC lower operating temperature than IC1?

Solution:Step 1: Write the equations:

(1) --- Taveg = (T1 + T2)/2 = 65;(2) --- T1 – T2 = 10;

Step 2: Solve the equations Rewrite equation (2) as equation (3) T1 = 10 + T2 Substitute (3) into (1)

Taveg = (10+T2+T2)/2 = 6510 + 2T2 = 1302T2 = 120T2 = 60ºCNow, we substitute T2 into (2) to solve T1 = 10 + T2 = 70ºC

Page 33: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 33© Chathura De Silva, Dept. of Computer Science and Engineering

Writing and Evaluating Math.Equations in MATLAB Operators (cont.)

Example 2-5:

Step 3: Verify the solution using MATLAB>> T1 = 70;>> T2 = 60;>> (T1 + T2)/2ans

= 65>> T1 – T2ans

= 10

Page 34: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 34© Chathura De Silva, Dept. of Computer Science and Engineering

Example 2-6: Graph the line y = a x + b, where b is called the offset (b = 0), a is called the slope (a = 3), and x is in the following range: -20 ≤ x ≤ 20.

Solution:n Need several steps.n We will later se how we

can automate these command sequences using a script file

Writing and Evaluating Math.Equations in MATLAB Operators (cont.)

Page 35: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 35© Chathura De Silva, Dept. of Computer Science and Engineering

Writing and Evaluating Math.Equations in MATLAB Operators (cont.)

Page 36: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 36© Chathura De Silva, Dept. of Computer Science and Engineering

MatLab Desktop Environment

Page 37: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 37© Chathura De Silva, Dept. of Computer Science and Engineering

Desktop Tools

Started MATLAB and see the three sub-windows:n Command Windown Current Directoryn Command HistoryAt the commandwindow, we enter>>help help

Page 38: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 38© Chathura De Silva, Dept. of Computer Science and Engineering

Command Window

n Running Functionsn Entering Variablesn Controlling Input/Outputn Searching Itemsn Running Programsn Setting Preferences for the Command

Window

Page 39: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 39© Chathura De Silva, Dept. of Computer Science and Engineering

Running Commands

An Example:>> magic(3)ans =

8 1 6

3 5 7

4 9 2

>> help magic>> help magic

MAGIC MAGIC MagicMagic square.square.MAGIC(N) is an NMAGIC(N) is an N--byby--N N

matrix constructed from the matrix constructed from the integersintegers

1 through N^2 with equal 1 through N^2 with equal row, column, and diagonal row, column, and diagonal sums.sums.

Produces valid magic Produces valid magic squares for all N > 0 except N squares for all N > 0 except N = 2.= 2.

15

15

15

15 1515 15 15

Page 40: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 40© Chathura De Silva, Dept. of Computer Science and Engineering

Entering Variables

>> x = 10x = 10>> y = 10y = 10>> x * yans = 100>> x / yans = 1>> x + yans = 20>> x - yans = 0>>

Page 41: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 41© Chathura De Silva, Dept. of Computer Science and Engineering

Controlling Input/Output

Format Function – control the display formats for numeric values

n Examples>> x = 1/3x = 0.3333

>> y = 1.2345e-7y = 1.2345e-7

>> format short e>> xx = 3.3333e-001>> yy = 1.2345e-007

Hit Enter keyHit Enter key

MATLAB DisplaysMATLAB Displays

Hit Enter keyHit Enter key

MATLAB DisplaysMATLAB Displays

Hit Enter keyHit Enter key

Enter xEnter x

Enter yEnter y

MATLAB EchoesMATLAB Echoes

Page 42: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 42© Chathura De Silva, Dept. of Computer Science and Engineering

Controlling Input/Output (continue)

n Format Function:>> help format

FORMAT Set output format.All computations in MATLAB are done in double

precision.FORMAT may be used to switch between

different outputdisplay formats as follows:

FORMAT Default. Same as SHORT.FORMAT SHORT Scaled fixed point format with 5 digits.FORMAT LONG Scaled fixed point format with 15 digits.FORMAT SHORT E Floating point format with 5 digits.FORMAT LONG E Floating point format with 15 digits.

>> format long>> xx =

0.33333333333333>> yy =

1.234500000000000e-007

Page 43: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 43© Chathura De Silva, Dept. of Computer Science and Engineering

Controlling Input/Output (continue)

n Format Function:>> help format

… FORMAT SHORT G Best of fixed or floating point format with 5 digits.FORMAT LONG G Best of fixed or floating point format with 15 digits.FORMAT HEX Hexadecimal format.FORMAT + The symbols +, - and blank are printed for positive, negative and zero elements. Imaginary parts are ignored.FORMAT BANK Fixed format for dollars and cents.FORMAT RAT Approximation by ratio of small integers.

>> format long g>> xx = 0.333333333333333>> yy = 1.2345e-007>> format bank>> xx = 0.33>> yy = 0.00>> format rat>> xx = 1/3 >> yy = 1/8100446

Page 44: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 44© Chathura De Silva, Dept. of Computer Science and Engineering

Controlling Input/Output (continue)

File File --> Preferences> Preferences

••Allows you to set Allows you to set up various up various numeric display numeric display formats through formats through GUIGUI

Page 45: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 45© Chathura De Silva, Dept. of Computer Science and Engineering

Suppress Output

n Suppressing Outputn End of the statement with a semicolonn Increase statement and program

execution speed n An Example>> x = 10;>> y = 10;>> product = x * yProduct = 100

Page 46: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 46© Chathura De Silva, Dept. of Computer Science and Engineering

Entering long Statements

n If a statement does not fit on a line (too long), uses an ellipsis (three periods), follow by Enter or Return, to indicate the continuation of the statement to the next line

n For an example>> x = 1 + 2 + 3 + 5 + 6 + 7 + ...8 + 9 + 10x =

51

Page 47: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 47© Chathura De Silva, Dept. of Computer Science and Engineering

Command Line Editing and Command History

n Command Line Editing Keys such as right arrow ? , down arrow ?, up arrow ?, left arrow ? , etc, can be used to edit commands

n Command Historyn The entered commands at the Command

Windows are recorded or logged in the Command History

n We can view previous commands or statements

n We can copy or execute rerun previous statements

Page 48: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 48© Chathura De Silva, Dept. of Computer Science and Engineering

The MATLAB Workspace

n who functionn whos functionn clear function

>> whoYour variables are:x y

>> whosName Size Bytes Class

x 1x1 8 double arrayy 1x1 8 double array

Grand total is 2 elements using 16 bytes>> clear x>> whoYour variables are:y

>> clear>> whos

Page 49: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 49© Chathura De Silva, Dept. of Computer Science and Engineering

The MATLAB Workspace

n save functionn load function

>> save 8_20_2004.mat>> clear>> whos>> load 8_20_2004.mat>> whosName Size Bytes Class

ans 1x1 8 double arrayx 1x1 8 double arrayy 1x1 8 double array

Grand total is 3 elements using 24 bytes

>> clear>> whos

Current Directory

Page 50: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 50© Chathura De Silva, Dept. of Computer Science and Engineering

Save Command

n We can use “help save” to see documentation of SAVE function and learn how to Save workspace variables to disk. n SAVE FILENAME saves all workspace variables

to the binary "MAT-file“, If FILENAME has no extension, .mat is assumed.

n SAVE, by itself, creates the binary "MAT-file" named 'matlab.mat'. It is an error if 'matlab.mat' is not writable.

n SAVE FILENAME X saves only X.n SAVE FILENAME X Y Z saves X, Y, and Z. The

wildcard '*' can be used to save only those variables that match a pattern.

Page 51: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 51© Chathura De Silva, Dept. of Computer Science and Engineering

Save Command (continue)

MATLAB also offers various saving options: n ASCII Options:

n SAVE ... -ASCII uses 8-digit ASCII form instead of binary regardless of file extension.

n SAVE ... -ASCII -DOUBLE uses 16-digit ASCII form.

n SAVE ... -ASCII -TABS delimits with tabs.n And more will be discussed later

Page 52: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 52© Chathura De Silva, Dept. of Computer Science and Engineering

Help Browser

Page 53: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 53© Chathura De Silva, Dept. of Computer Science and Engineering

Workspace Browser

Page 54: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 54© Chathura De Silva, Dept. of Computer Science and Engineering

Current Directory Browser

Page 55: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 55© Chathura De Silva, Dept. of Computer Science and Engineering

The Edit/Debug

n Use the Editor/Debugger to create and debug M-files, which are programs you write to run MATLAB functions.

n The Editor/Debugger provides a graphical user interface for basic text editing, as well as for M-file debugging.

Page 56: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 56© Chathura De Silva, Dept. of Computer Science and Engineering

The Edit/Debug (continue)

Page 57: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 57© Chathura De Silva, Dept. of Computer Science and Engineering

The Edit/Debug (continue)

Create a mlab_exs directory

Save the M-file as sine60hz.m

Page 58: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 58© Chathura De Silva, Dept. of Computer Science and Engineering

The Edit/Debug (continue)

Page 59: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 59© Chathura De Silva, Dept. of Computer Science and Engineering

Testing/Debugging sin60hz.m

Click -> Debug -> Run

Page 60: Introduction to matlab

CS428 – Introduction to prg. Using MatLab 60© Chathura De Silva, Dept. of Computer Science and Engineering

Other Commands

n Other Useful MATLAB Management Commands/Functions

n Demo - Run demosn help - Online helpn ver - Current MATLAB and toolbox

versionsn version - Current MATLAB version

numbern path - MATLAB Search pathn diary - Save typed commands on a

named file