math 98 - introduction to matlab programming

24

Upload: trandat

Post on 27-Dec-2016

245 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Math 98 - Introduction to MATLAB Programming

Math 98 - Introduction to MATLAB Programming

Fall 2016 - Lecture 1

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 2: Math 98 - Introduction to MATLAB Programming

Syllabus

Instructor: Chris Policastro

Class Website:https://math.berkeley.edu/~cpoli/math98/fall2016.html

See website for

1 Class Number

2 O�ce hours

3 Textbooks

4 Lecturescheduleslidesprograms

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 3: Math 98 - Introduction to MATLAB Programming

Syllabus

Class Website:https://math.berkeley.edu/~cpoli/math98/fall2016.html

See website for

1 Homeworkgrading policyscheduleassignmentssolutions

Homework Submission:https://bcourses.berkeley.edu

See bCourses site for

1 Suggestions and hints on the homework and project.

2 Homework must be submitted by 11:59pm

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 4: Math 98 - Introduction to MATLAB Programming

Syllabus

Class Website:https://math.berkeley.edu/~cpoli/math98/fall2016.html

See website for links to the documentation

1 Language fundamentals:http://www.mathworks.com/help/matlab/language-fundamentals.html

syntaxoperatorsdata typesarray indexing and manipulation

2 Programming Scripts and Functionshttp://www.mathworks.com/help/matlab/

programming-and-data-types.html

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 5: Math 98 - Introduction to MATLAB Programming

Getting started with MATLAB

MATLAB has �ve features:

1 Command Window is a programmable calculator with broad capabilities.Here we can perform calculations, de�ne variables, debug and much more.

2 Editor allows us to write collections of commands and save them asM-�les.

3 Current Directory shows the �les that MATLAB is accessing. By defaultMATLAB cannot execute �les contained in other folders.

Use pwd to check current directoryUse dir to check contents

4 Workspace is a MAT-�le containing the variables you have de�ned in yoursession.

5 Command History Can be accessed using up arrow. It should be closed inthe interface.

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 6: Math 98 - Introduction to MATLAB Programming

Lecture 1: Turning formulas into programs

1 Problems(problem_1_1) Surface area of a sphere (Chapter 1.1 van Loan)(problem_1_2) Minimum of quadratic polynomial on an interval (Chapter1.2 van Loan)

2 Conceptsvariable, initialization, arithmetic, stringconditional, logical expression, boolean expression

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 7: Math 98 - Introduction to MATLAB Programming

(problem_1_1) Surface area of a sphere

The formula for the surface area of a sphere of radius r is

A(r) = 4πr2

For large values of r, the numbers r and r2 di�er by a large amount. Thefactor r2 in the formula implies that a small change in r (call it δr) a�ects alarge change in surface area (call it δA)

We want to study δA as a function of δr to illustrate rounding errors throughcomparison of the (approximate) formulas

1 4π(r + δr)2 − 4πr2

2 4π(2r + δr) · δr3 8πr · δr

for δA.

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 8: Math 98 - Introduction to MATLAB Programming

Arithmetic

Operations: +,−, ∗, /, ·̂.

(2− 3 ∗ (5− 4)) ∗ 4/5 =4

5(2− 3(5− 4))

1/2/3/4 = ((1/2)/3)/4.

Order of operations goes parentheses, division, multiplication,addition/subtraction

2 + 3, 2− 3, 2/3, 2× 3,23,21/3

log2 3, π3

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 9: Math 98 - Introduction to MATLAB Programming

Command line

Use a semicolon to suppress the output of command.

Multiple commands can be placed on a line separated by commas or semicolons.

sqrt(5); abs(−3), sign(−10);

Use SHIFT-ENTER to start a new line. Use ellipses (. . . ) and SHIFT-ENTERto continue a line.

Ellipses cannot be inserted anywhere e.g.

sqrt(5...

);

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 10: Math 98 - Introduction to MATLAB Programming

Variables

The value of an arithmetic expression is saved as ans.

ans is a variable whose value is stored in the Workspace.

The Workspace is an example of a MAT-�le, which is a special �le thatcontains MATLAB data.

Variables can be de�ned by

Variable_Name = Value for example r=6367

This is called initializing a variable.

MATLAB is case sensitive. However all built-in MATLAB functions use lowercase letters. Therefore try to use at least one capital letter to avoid con�ict(e.g. Abs not abs)

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 11: Math 98 - Introduction to MATLAB Programming

Example

1 %%%Sur faceArea .m%%%2 %3 % Computes s u r f a c e a r ea o f s phe r e o f r a d i u s r4 % User i s prompted to i npu t r5

6 r=i npu t ( ' Ente r r a d i u s r : ' ) ;7 A=4∗p i ∗ r ^2;8 f p r i n t f ( ' r = %10.3 f A = %10.3 e\n ' , r ,A) ;

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 12: Math 98 - Introduction to MATLAB Programming

Scripts and m-�les

A script is a short computer program, that is, a procedure implemented as asequence of instructions for the computer.

The order of the instructions is important.

An m-�le is a �le containing a script for MATLAB.

The name of the �le must have the format filename.m. For MATLAB toexecute the �le, it must be saved in the Current Directory.

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 13: Math 98 - Introduction to MATLAB Programming

input

A string is a sequence of characters enclosed by single quotation e.g.`stringexample&)'

The command input will prompt the user to input a number or string.

If the input should be a string, then use

input('exampleinstructions ','s')

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 14: Math 98 - Introduction to MATLAB Programming

fprintf

The command fprintf is used to display formatted strings that incorporatespeci�ed values

fprintf('formattedstring',listofvariables)

The formats are %d for integer, %e for scienti�c notation, and %f for decimalformat.

fprintf('Temperature = %4d Pressure = %5.9f \n',T,P)

\n is to start a new line.

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 15: Math 98 - Introduction to MATLAB Programming

Commenting with %

Except within a string, everything following % is a comment. Commentsfacilitate the reading of code by providing information about the organization.Comments should always appear at the beginning of a document.

Providing comments is called documenting. Using explanatory �le names andvariable names helps with documenting.

temp for a temporary variable not auehh125

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 16: Math 98 - Introduction to MATLAB Programming

Review of problem_1_1

There are two sources of error in the calculation from problem_1_1.

1 π is an irrational number meaning its decimal expansion continues withoutrepeating. A computer can only process irrational numbers throughapproximation by rational numbers.

2 Even rational numbers are rounded in MATLAB. Think of a calculatorrendering 1 divided by 3 as .3333. This error is carried through acalculation.

The sources of error account for

1 The di�erence between method 1 and method 2

2 The nearness of method 1 and method 3

Note the large change in surface area from small change in radius. Compare tothe surprising fact that increasing circumference by 2πδ means increasing theradius by δ.

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 17: Math 98 - Introduction to MATLAB Programming

exercise_1_1

A temperature can be converted from the Fahrenheit scale into the Celsiusscale using the formula

c = (5/9)(f − 32) where c is Celsius and f is Farenheit

Write a script that prompts the user for a temperature in Farhenheit, convertsit to Celsius and prints it.

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 18: Math 98 - Introduction to MATLAB Programming

(problem_1_2) Minimum of quadratic polynomial on an interval

A quadratic polynomial has form f(x) = x2 + bx+ c. It attains minimum overR at x = −b/2. On an interval [L,R] the minimum may be attained at one ofthe end points.

We want to write a program that will

1 prompt the user for a quadratic polynomial x2 + bx+ c

2 prompt the user for an interval [L,R]

3 compare the values of −b/2, L and R

4 print the location of the minimum on the interval

For this we need to know about conditional statements.

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 19: Math 98 - Introduction to MATLAB Programming

Relations

The following statements take value 0 or 1

a<b a less than b

a>b a less than or equal to b

a<=b a greater than or equal to b

a>=b a greater than or equal to b

a==b a equal to b

a ∼= b a not equal to b

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 20: Math 98 - Introduction to MATLAB Programming

Logical statements

1 and(a,b) equivalently a & b

2 or(a,b) equivalently a|b

3 not(a)

4 xor(a,b)

What do the commands && and || do?

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 21: Math 98 - Introduction to MATLAB Programming

boolean expression

A boolean expression is any expression involving relations or logical statements

((4 <= 100)|(−2 >= 7))& (0.5 == 1e16)

A boolean expression takes the values 1 (for true) and 0 (for false). Note that0 and 1 are just number; there does not exist a separate class for them.

The order of operations for evaluations of boolean expressions is

1 negation

2 relations (<, =,...)

3 and

4 or

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 22: Math 98 - Introduction to MATLAB Programming

if-else

The construct is used in situations where the decision to choose between a pairof alternative computations is based upon a boolean expression

1 i f boo l ean e x p r e s s i o n2

3 command to be execu ted when e x p r e s s i o n i s t r u e4

5 e l s e6

7 command to be execu ted when e x p r e s s i o n i s nott r u e

8

9 end

See van Loan and Fan for a variant on the construction using if-elseif-else

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 23: Math 98 - Introduction to MATLAB Programming

Review of problem_1_2

Just as arithmetic comes with rules such as

1 order or operations

2 association

3 distribution...

manipulations with boolean expressions have rules such as

1 order or operations

2 association

3 distribution...

By taking to 0 to be false and 1 to be true, we can represent booleanexpressions on a computer. These expressions are the ingredients of conditionalstatements, which execute commands based on the validity of booleanexpressions.

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming

Page 24: Math 98 - Introduction to MATLAB Programming

exercise_1_1

A string can be inserted into another string using fprintf. The place holderfor a string is %s.

Take Str='MATH98'. fprintf('%s is a class',Str) would printMATH98 is a class to the command window.

Write a script that prompts the user for two numbers. Call them x and y. Usean if-else statement to determine whether x equals y. Output eitherThe numbers are equal or The numbers are not equal to the commandwindow.

Fall 2016 - Lecture 1 Math 98 - Introduction to MATLAB Programming