110 likes | 289 Views
COMP 116: Introduction to Scientific Programming . Lecture 2: Getting started with MATLAB a s a Caculator a s a programming language. What we will cover. Use MATLAB as a calculator Arithmetic operators +, -, *, /, , ^ Precedence Rules Parenthesis, nesting, left-right, + -, * /
E N D
COMP 116: Introduction to Scientific Programming Lecture 2: Getting started with MATLAB as a Caculator as a programming language
What we will cover • Use MATLAB as a calculator • Arithmetic operators +, -, *, /, \, ^ • Precedence Rules Parenthesis, nesting, left-right, + -, * / • Built-in Math functions sin, abs, rem, etc. • Built-in constants pi, ans, inf, … • (Very simple) Programming • Assignment: <variableName> = <expresssion>
Arithmetic operators • Type doc ops or doc arithat prompt for more info
Simple Operator Precedence P E M D A S Mnemonic: PEMDAS • Examples: • >> 1 + 2 * 3 • >> (1 + 2) * 3 • >> 5 – (6 * (4 + 2)) • >> 5 – 3 ^ 2 * -7 • Type doc precedence or search for precedence in help for more info… • Ans = 7 (not 9). This expression is the same as 1 + (2*3) • Ans = 9 (not 7) • Ans = -31 • Ans = 68 same as (5 – ((3^2) * (-7)))
Simple Functions functionName(input) Or functionName(input1, input2) Try: >> sin( pi/2 ) >> abs( cos( pi ) ) >> 27 + exp( 2 ) >> power( 8, 3 )
Useful Math Built-in Functions • Elementary Math Functions: • sqrt(x), abs(a), … • Trigonometric: • sin, cos, tan, csc, sec, cot, acos, atan2 • Rounding and Remainder: • round, ceil, floor, rem(x,y), mod(a,b) • Exponential / Logarithmic: • exp, expm1, log, log1p, log10, log2 • Random Numbers: • rand, rand(m,n), rand(m) • Try doc elfun for more info…
What we will cover • Use MATLAB as a calculator • Arithmetic operators +, -, *, /, \, ^ • Precedence Rules Parenthesis, nesting, left-right, + -, * / • Built-in Math functions sin, abs, rem, etc. • Built-in constants pi, inf, … • (Very simple) Programming • Assignment: <variableName> = <expresssion>
First Programming Concept:Assign values to variables Assignment: LHS= RHS means evaluate RHS and assignthis value to the variable LHS Example: >> x = 32 • In Math: the value of x is 32 • In Programming: assign the value 32 to the variable x >> x = 7 >> y = 32 >> z = x + y • We will learn (much) more about this in the classes to come
Math programming fun • The golden ratio appears in a lot of places • Architecture, spirals, Fibonacci numbers etc. • Its value is 1.6180339887……. • And it satisfies • Start with any positive value of x, say 10000 • Repeatedly assign sqrt(x+1) to the variable x i.e. • >> x=sqrt(x+1) • What do you see?