Intro to Matlab 1.Using scalar variables 2.Vectors, matrices, and arithmetic 3.Plotting 4.Solving...

30
Intro to Matlab 1. Using scalar variables 2. Vectors, matrices, and arithmetic 3. Plotting 4. Solving Systems of Equations Can be found at: http://www.cs.unc.edu/~kim/matlab.ppt

Transcript of Intro to Matlab 1.Using scalar variables 2.Vectors, matrices, and arithmetic 3.Plotting 4.Solving...

Intro to Matlab

1. Using scalar variables

2. Vectors, matrices, and arithmetic

3. Plotting

4. Solving Systems of Equations

Can be found at: http://www.cs.unc.edu/~kim/matlab.ppt

New Class--for Engineers

• ENGR196.3

• SPECIAL TOPICS: INTRODUCTION TO MATLAB

• Description: Fundamentals of MATLAB programming applied to problems in science and mathematics. Solving systems of equations, basic scripting, functions, vectors, data files, and graphics. (Credit course for grade or CR/NC)

Why use Matlab?

• Drawbacks:

Slow (execution) compared to C or Java

• Advantages:

Handles vector and matrices very nice

Quick plotting and analysis

EXTENSIVE documentation (type ‘help’)

Lots of nice functions: FFT, fuzzy logic, neural nets, numerical integration, OpenGL (!?)

One of the major tools accelerating tech change

A tour of Matlab’s features• Click on Help>Full Product Family Help:

Check out Fuzzy Logic

Genetic Algorithms

Symbolic Math

Scalars

• The First Time You Bring Up MATLAB

• MATLAB as a Calculator for Scalars

• Fetching and Setting Scalar Variables

• MATLAB Built-in Functions, Operators, and Expressions

• Problem Sets for Scalars

3-1 The First Time You Bring Up MATLAB

Basic windows in MATLAB are:• Command - executes single-line commands• Workspace - keeps track of all defined variables• Command History - keeps a running record of all single

line programs you have executed• Current Folder - lists all files that are directly available for

MATLAB use• Array Editor - allows direct editing of MATLAB arrays• Preferences - for setting preferences for the display of

results, fonts used, and many other aspects of how MATLAB looks to you

3-2 MATLAB as a Calculator for Scalars

• A scalar is simply a number…

• In science the term scalar is used as opposed to a vector, i.e. a magnitude having no direction.

• In MATLAB, scalar is used as opposed to arrays, i.e. a single number.

• Since we have not covered arrays (tables of numbers) yet, we will be dealing with scalars in MATLAB.

,4,7

22,5.3

3-3 Fetching and Setting Scalar Variables

• Think of computer variables as named containers.

• We can perform 2 types of operations on variables:

we can set the value held in the container: x = 22we can set the value held in the container: x = 22

we can look at the value held in the container: xwe can look at the value held in the container: x

The Assignment Operator (=)

• The equal sign is the assignment operator in MATLAB.

>> x = 22places number 22 in container x

• How about:>> x = x + 1

• Note the difference between the equal sign in mathematics and the assignment operator in MATLAB!

Useful Constants

• Inf infinity• NaN Not a number (div by zero)• eps machine epsilon• ans most recent unassigned answer• pi 3.14159….• i and j Matlab supports imaginary

numbers!

Using the Command History Window

3-4 MATLAB Built-in Functions, Operators, and Expressions

• MATLAB comes with a large number of built-in functions (e.g.. sin, cos, tan, log10, log, exp)

• A special subclass of often-used MATLAB functions is called operators– Assignment operator (=)– Arithmetic operators (+, -, *, /, ^)– Relational operators (<, <=, = =, ~=, >=, >)– Logical operators (&, |, ~)

Example – Arithmetic Operators

Hint: the function exp(x) gives e raised to a power x

Example – Relational and Logical Operators

Vector Operations

Chapter 5

Vector Operations

• Vector Creation

• Accessing Vector Elements

• Row Vectors and Column Vectors, and the Transpose Operator

• Vector Built-in Functions, Operators, and Expressions

Vectors and Matrices• Can be to command line or from *.m file

scalar: x = 3vector: x = [1 0 0]2D matrix: x = [1 0 0; 0 1 0; 0 0 1]arbitrarily higher dimensions (don’t use much)

• Can also use matrices / vectors as elements:

x = [1 2 3]

y = [ x 4 5 6]

2-D Plotting and Help in MATLAB

Chapter 6

2-D Plotting and Help in MATLAB

• Using Vectors to Plot Numerical Data

• Other 2-D plot types in MATLAB

• Problem Sets for 2-D Plotting

6-2 Using Vectors to Plot Numerical Data• Mostly from observed data - your goal is to

understand the relationship between the variables of a system.

• Determine the independent and dependent variables and plot:

speed = 20:10:70;stopDis = [46,75,128,201,292,385];plot(speed, stopDis, '-ro') % note the ‘-ro’ switch

• Don’t forget to properly label your graphs:title('Stopping Distance versus Vehicle Speed', 'FontSize', 14)xlabel('vehicle speed (mi/hr)', 'FontSize', 12)ylabel('stopping distance (ft)', 'FontSize', 12)grid on

Speed (mi/hr) 20 30 40 50 60 70

Stopping Distance (ft) 46 75 128 201 292 385

Sample Problem – Plotting Numerical Data

3D Plotting• 3D plots – plot an outer product

x = 1:10y = 1:10z = x’ * ymesh(x,y,z)

Single quote ‘ means transpose (can’t cut and paste though…)

Flow Constructs

• IF block

if (<condition>)

<body>

elseif

<body>

end

• WHILE block

while (<condition>)

<body>

end

Conditions same as C, ( ==, >=, <=) except != is ~=

More Flow Constructs

• FOR block

for i = 1:10

<body>

end

• SWITCH statement

switch <expression>

case <condition>,

<statement>

otherwise <condition>,

<statement>

end

Other Language Features

• Matlab language is pretty sophisticated– Functions

Stored in a *.m file of the same name:

function <return variable> = <function name>(<args>)

<function body>

– Structs• point.x = 2; point.y = 3; point.z = 4;

– Even has try and catch (never used them)

Solving Systems of Equations

• Consider a system of simultaneous equations

3x + 4y + 5z = 32

21x + 5y + 2z = 20

x – 2y + 10z = 120

• A solution is a value of x, y, and z that satisfies all 3 equations

• In general, these 3 equations could have

1 solution, many solutions, or NO solutions

Using Matlab to Solve Simultaneous Equations

• Set up the equation in matrix/vector form:

A = [3 4 5; 21 5 2; 1 -2 10] u = [ x y z]’ b = [ 32 20 120]’In other words, A u = b (this is linear algebra)

3 4 5

21 5 2

1 -2 10

x

y

z

*

32

20

120

=

The solution uses matrix inverse

• If you multiply both sides by 1/A you get

u = 1/A * b

• In the case of matrices, order of operation is critical (WRONG: u = b/A )

• SO we have “Left division” u = A \ b

(recommended approach)

• OR use inv( ) function: u = inv(A) * b

The solution>> u = A\b

u =

1.4497 ( value of x)

-6.3249 ( value of y)

10.5901 ( value of z)

• You can plug these values in the original equation test = A * u and see if you get b

Caution with Systems of Eqs

• Sometimes, Matrix A does not have an inverse:

• This means the 3 equations are not really independent and there is no single solution (there may be an infinite # of solns)

• Take determinant det(A) if 0, it’s singular

1 -1 0

1 0 -1

0 1 -1

x

y

z

*

32

10

22

=