Sunteți pe pagina 1din 40

InteractiveM ATLAB Numeric data logical operators Other data types

Basic M ATLAB

Isaac Ye

UOIT

MATH 2070U
InteractiveM ATLAB Numeric data logical operators Other data types

Basic M ATLAB

Interactive computing in M ATLAB


Arithmetic operators and order of operations
Identifiers and reserved words in M ATLAB
Common mathematical functions in M ATLAB

Numeric data
Numeric arrays
Matrix and array operators

Boolean/logical operators

Other data types: char/string, polynomials, & heterogeneous


types
InteractiveM ATLAB Numeric data logical operators Other data types

Key questions

• How do I use M ATLAB as a numerical calculator?


• What rules define interactive computing with M ATLAB?
• How do I use the on-line help?
• How do arrays & matrices work in M ATLAB?
• What are logical/Boolean variables and operators?
• What other data types exist in M ATLAB?
InteractiveM ATLAB Numeric data logical operators Other data types

Entering expressions interactively


Execute the following statements & explain

>> a = 4; % assigns value 4 to variable a


>> a = a + 1.42644 % assigns value 5.42644 to variable a
>> b = a, b = ... % command continued on next line
>> 3

>> command prompt


= assignment operator
; statement separator (suppress output)
, statement separator (with output)
... continuation of statement on next line
ans last value calculated (“answer”)
% comment symbol; characters to right ignored
(extra spaces don’t matter within statements)
InteractiveM ATLAB Numeric data logical operators Other data types

Arithmetic operators

• Arithmetic operations are the simplest ones we know:


(addition, subtraction, multiplication, division, and
exponentiation)
+ Addition
- Subtraction
* Multiplication
/ Division
^ Raising to a power
• Arithmetic operators can be used to join together
expressions to yield larger mathematical expressions
InteractiveM ATLAB Numeric data logical operators Other data types

Order of operations

• Expressions are evaluated from left to right in order of


1. exponentiation (^) first;
2. division (/) next;
3. multiplication (*) next;
4. subtraction (-) next;
5. addition (+) last
• Parentheses supersede order of operations: apply the rules
above within the innermost parentheses first and proceed
outward
InteractiveM ATLAB Numeric data logical operators Other data types

Order of operations

Execute highlighted commands to verify results

42 −145
 
3
1-5*4^2/3+3/2 = 1 − 5 × + =
3 2 6
' −24.16666667
 2
 3 √
3 3
1-5*4^(2/3)+3/2 = 1 − 5 × 4 3 + = 1 − 5 42 +
2 2
' −10.09921050
InteractiveM ATLAB Numeric data logical operators Other data types

Typesetting expressions for programs

• Use ASCII (”typewriter”) characters for programming.


• Arithmetic operations of addition, subtraction,
multiplication, division, and exponentiation are +, -, *, /,
and ^ respectively
• e.g. the expressions below have are typeset as specified
x+y x+y
b−a b-a
uv = u × v u*v
m
m/n = m ÷ n = m/n
n
ak a^k
• (Some languages allow a**k for ak , e.g., M APLE & Fortran)
InteractiveM ATLAB Numeric data logical operators Other data types

Identifiers in M ATLAB

• Identifier: generic term for “variable name” in


programming
• Rules for identifiers in M ATLAB:
1. Identifiers are case sensitive (e.g., Alpha6=alpha)
2. Identifiers can contain up to 63 characters. Any character
beyond the 63rd is ignored.
3. Identifiers must start with a letter, followed by any number
of letters, digits, or underscores. Punctuation characters are
not allowed. (e.g., foo 4 is allowed, but not foo4 or 4foo)
• Use sensible identifiers term to clarify code, e.g.,
area = pi*radius^2
volume = length * height * width
amount owing = principal + interest
InteractiveM ATLAB Numeric data logical operators Other data types

Reserved words
• In every programming language, some names should not
or cannot be used as identifiers since they are already
reserved for some other purpose; these names are
keywords or reserved words
• e.g., identifier pi in M ATLAB reserved for
π ' 3.1415926535897932
• e.g., identifier tan in M ATLAB reserved for tangent
function
• Other reserved words in M ATLAB: for, while, if, else,
end, etc.
• Warning: Some programming languages (including
M ATLAB) let you redefine identifiers associated with
reserved words. Avoid doing this unless you have a good
reason and you know what you are doing!
InteractiveM ATLAB Numeric data logical operators Other data types

Reserved words (cont.)

• Notations vary in programming languages


• e.g., in M ATLAB, π is pi; in M APLE, π is Pi
• e.g., log means ln = loge in some languages but, in others,
log means log10 or log2

Moral:
If you don’t remember the exact identifier for a given function
or constant or feature in a given programming language, make
sure you know how to look it up! In interpretive programming
languages, this means that online help is your friend!

In M ATLAB, use help, doc, or lookfor.


InteractiveM ATLAB Numeric data logical operators Other data types

Syntax for common mathematical functions



sqrt(x) square root x

nthroot(x,n) nth root n x = x1/n
exp(x) exponential function ex = exp(x)
abs(x) absolute value |x|
log(x) natural logarithm ln x = loge x
log10(x) base 10 logarithm log10 (x)
cos(x) cosine function cos x
sin(x) sine function sin x
tan(x) tangent tan x
cosh(x) hyperbolic cosine function cosh x
sinh(x) hyperbolic sine function sinh x
tanh(x) hyperbolic tangent function tanh x
InteractiveM ATLAB Numeric data logical operators Other data types

Examples of typeset mathematical expressions

2x + cos2 y
(2*x + cos(y)^2) / (3*x + 5*sin(y)^2)
3x + 5 sin2 y
p p
1 + 5φ − 1 + 2p
( sqrt( 1+5*phi ) - sqrt( 1+2*p ) ) / p
p

eln 5/(3+7 ln α) exp( ( log(5) / ( 3 + 7*log(alpha) ) )


1. Parentheses explicitly surround function arguments
2. Functions may have multiple arguments separated by
comments
e.g. f (x, y) translates to f(x,y)
3. Customary to spell out Greek letters,
α 7→ alpha, β 7→ beta, etc.
InteractiveM ATLAB Numeric data logical operators Other data types

Common programming mistakes!

• Multiplication requires * explicitly


e.g., 2x3 − 4x2 + 7x − 1 7→ 2*x^3-4*x^2+7*x-1
• Parentheses explicitly needed to specify function arguments
e.g., cos 2θ 7→ cos(2*theta) (not cos2theta or cos2*theta)
• Trigonometric functions cos, sin, etc. use radian measure
(use cosd(x), sind(x), etc., if x is angle in degrees)
• ln x 7→ log(x) (not lnx or ln(x))
• sin2 z 7→ sin(z)^2 (not sin^2(z))
• ey 7→ exp(y) (not e^y)
• For multi-argument functions, order counts
e.g., nthroot(2, 3) 6= nthroot(3, 2)
InteractiveM ATLAB Numeric data logical operators Other data types

The most important commands!

When in doubt, use online help!

help Used to extract information about internal M ATLAB


functions and user-written functions

doc Similar to help, launches graphical help browser

lookfor very useful when you don’t know the name of the
command but you have pertinent keywords
InteractiveM ATLAB Numeric data logical operators Other data types

The format command in M ATLAB


• format is used to specify output precision
Execute the following statements & explain
s = [1/2 1/3 pi sqrt(2)];
format short; s
format long; s
format rat; s
format bank; s

• See help format or doc format

Warning:
format affects output to screen only!
Internal representation in M ATLAB is different
InteractiveM ATLAB Numeric data logical operators Other data types

The diary command in M ATLAB


• diary preserves screen output of interactive session
Execute the following statements & explain

>> diary on % Start writing diary file


>> a = 5; b = 2; c = 1;
>> discr = sqrt(b^2 - 4*a*c);
>> x1 = 1/(2*a)*(-b + discr)
>> diary off % Stop writing to diary file

• Useful for record of interactive session when experimenting


• diary on starts recording session to text file diary
• diary(’file.txt’) starts recording session to text file file.txt
• diary off stops recording session to diary file
• Only screen input/output preserved; computations are
discarded
InteractiveM ATLAB Numeric data logical operators Other data types

Real numbers in M ATLAB


• By default, numeric data stored as real or complex
numbers
• (Special formats for integers require explicit casting)
• Scientific notation: mantissa × 10exponent
• Numbers in scientific notation are entered entering the
mantissa and exponent separated by the character e
2←exponent
| {z } ×10
e.g., 739.432 = 7.39432
mantissa
would be entered in M ATLAB as
>> 7.39432e2
Number mantissa & exponent M ATLAB form
0.0001 1 × 10−4 1e-4
−5 −5 × 100 -5e0
472000000000 4.72 × 1011 4.72e11
InteractiveM ATLAB Numeric data logical operators Other data types

Entering complex numbers



• Complex numbers a + ib with i = −1, a, b ∈ R
• By default, symbols i & j are sqrt(-1)
Execute the following statements & explain

>> z = 2i, z^2


>> z1 = 2 + 3*i;
>> z2 = 2 + 3i; % 3i means 3*i *only* in this context
>> z3 = 2 + 3*sqrt(-1);
>> z1 - z2, z2 - z3 % Verifying z1==z2 & z2==z3
>> i = 3.5; % Assignment to i -> no longer i==sqrt(-1)
>> z4 = 2 + 3*i % Expect z4==12.5

Warning: i (and j) often overwritten


Be wary of assuming that i==sqrt(-1) (and/or j==sqrt(-1))
InteractiveM ATLAB Numeric data logical operators Other data types

Numeric functions for real and complex numbers

round(x) Round x to nearest integer


fix(x) Round x toward zero
floor(x) Round x toward minus infinity
ceil(x) Round x toward infinity
sign(x) Signum (sign function) of x

• Functions above convert real numbers to integers


• Applied to real/imaginary components of complex
numbers
• Implicitly vectorised (see later)
InteractiveM ATLAB Numeric data logical operators Other data types

Arrays

• Arrays are indexed lists of variables


• Correspond to vectors & matrices
• Vectors are one-dimensional arrays
• Matrices are two-dimensional arrays
• Arrays can be created by
• entering entries between brackets [ ] explicitly
• using specialised routines (e.g., ones, zeros, etc.)
• concatenating existing arrays as blocks
• Array elements accessed using parentheses ( )
InteractiveM ATLAB Numeric data logical operators Other data types

Entering arrays interactively


Execute the following statements & explain

>> A = [ 1, 2, 3 ; 4, 5, 6 ] % Creates 2x3 matrix A


>> B = [ 1 2 3 ] % Notice commas optional
>> C = [ B ; 4 5 6 ] % A and C are equivalent
>> v1 = [-1 2 -3 4], v2 = [-1,2,-3,4] % v1, v2 equivalent
>> v3 = [ -1 2 - 3 4 ] % v3 is different

Warning:
• ; (semicolon) separates rows within arrays (i.e., between [ ])
• , (comma) separates columns within arrays (i.e., between [ ])
• Outside arrays, semicolons & commas separate statements
• Infer correct meaning of symbols from context (help punct)
InteractiveM ATLAB Numeric data logical operators Other data types

Array indexing and column-major ordering


• Parentheses ( ) used for array indexing
• end refers to largest index in appropriate dimension
• M ATLAB uses column-major ordering for internal storage

Execute the following statements & explain

>> A = [ 1 2 3 4; 5 6 7 8; 9 10 11 12 ]
>> A(2,1) % returns 5
>> A(end, end-2) % returns 10
>> A(:) % Outputs entries of A as one-dimensional vector
>> A(7) % Makes sense even though A is 2D array

Warning:
• ( ) (parentheses) used for array indexing and function invocation
• Infer correct meaning of symbols from context
InteractiveM ATLAB Numeric data logical operators Other data types

Colon notation
• Colon notation is used to specify ranges of integer values
• Colon notation can specify larger steps
• Colon notation can specify ranges nonpositive steps
• Colon notation can specify non-integer ranges
• Colon notation can be used for indexing arrays
Execute the following statements & explain

>> 1:5 % creates row vector [ 1 2 3 4 5 ]


>> 1:2:10 % creates row vector [ 1 3 5 7 9 ]
>> 15:4:31 % creates [ 15 19 23 27 31 ]
>> 8:-2:3 % creates [ 8 6 4 ]
>> 0:0.1:0.5 % creates [ 0 0.1 0.2 0.3 0.4 0.5 ]
>> A = [ 1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16 ]
>> B = A(2:2:end, 2:3) % Extracts submatrix
InteractiveM ATLAB Numeric data logical operators Other data types

Commonly used M ATLAB commands for arrays

zeros array with all entries 0


ones array with all entries 1
rand, randn array with random entries
linspace vector with linearly spaced entries
logspace vector with logarithmically spaced entries
meshgrid replicated grids for 2D/3D computation

size integer vector of dimensions of array


length largest dimension of array
reshape reorders existing array elements into new shape
fliplr flips elements in left/right direction
flipud flips elements in up/down direction
repmat replicate or tile array
InteractiveM ATLAB Numeric data logical operators Other data types

Conformable arrays

• Arrays are conformable if they have the same shape


• e.g., A and C are conformable, but A and B are not
 
  1 2  
1 2 3 6 5 4
A= ,B = 3 4 ,C =
 
4 5 6 3 2 1
5 6

• Conformable arrays added/subtracted elementwise with +


and -
• Arrays can be multiplied by scalars in M ATLAB with *
InteractiveM ATLAB Numeric data logical operators Other data types

Matrix algebra

Standard matrix algebra operations

A+B matrix sum, A, B conformable arrays


A−B matrix difference, A, B conformable arrays
A∗B matrix product, A is m × n, B is n × p
A\B A−1 B, A is n × n nonsingular, B is n × p
A/B AB−1 , A is m × n, B is n × n nonsingular
c*A scalar multiplication, c scalar, A array
A^p matrix power, A is n × n, p scalar

(We’ll examine these in detail when studying numerical linear


algebra)
InteractiveM ATLAB Numeric data logical operators Other data types

Scalar expansion
• Scalar expansion in M ATLAB: mixed operations with
scalars and arrays lead to “expanding” scalar to
conformable array
• Scalar expansion inconsistent with conventions of linear
algebra
• Scalar expansion avoids unnecessary loops
Execute the following statements & explain

>> A = [ 1 2 3 ; 4 5 6 ];
>> A + 3.1 % Scalar expansion of sum
>> A.^2 % Scalar expansion of exponent
>> 2.^A % Scalar expansion of base
InteractiveM ATLAB Numeric data logical operators Other data types

Vectorised operations

Vectorised operators for elementwise operations (avoids loops)

A. ∗ B elementwise multiplication, A, B conformable arrays


A./B elementwise (right) division, A, B conformable arrays
A.\B elementwise (left) division, A, B conformable arrays
A.^B elementwise exponentiation, A, B conformable arrays

Vectorisation also combines with scalar expansion in the case of


elementwise division and exponentiation

c./A elementwise division, c scalar, A array


A./c elementwise division, c scalar, A array
A.^c elementwise exponentiation, c scalar, A array
InteractiveM ATLAB Numeric data logical operators Other data types

Important programming question

“What kind of data is stored in each variable?”


• Is it scalar data?
• Is it integer data? Real? Complex?
• Is it an array? If so, what dimensions?
• Is it some other data type?
• Are the operators used correctly?

• Vital skill for writing your own programs!


• Vital skill for reading programs of others!
InteractiveM ATLAB Numeric data logical operators Other data types

Logical operators
• Logical or boolean data: true (1) or false (0)
• Logical operators and truth tables
Syntax Meaning
and(a,b) a&b AND
or(a,b) a|b OR
not(a) ~a NOT
xor(a,b) XOR

and 0 1 or 0 1
0 0 0 0 0 1
1 0 1 1 1 1
not xor 0 1
0 1 0 0 1
1 0 1 1 0
InteractiveM ATLAB Numeric data logical operators Other data types

Relational operators: > < >= <= == ~=


• Comparison of quantities important in numerical
programming
e.g., to compute sin−1 (2x3 − 4), want |2x3 − 4| ≤ 1

Syntax Meaning
> (strictly) greater than
< (strictly) less than
>= greater than or equal to
<= less than or equal to
== equal to
~= not equal to
• Relational operators compare two numeric quantities
• Assignment operator = distinct from comparison ==
• (More on logical variables when looking at control flow)
InteractiveM ATLAB Numeric data logical operators Other data types

Assignment operator

Warning: = and == have distinct meanings!


• = is assignment operator:

A=B means contents of B copied (overwritten) into A

Assigns value to identifier on left-hand-side


• == is logical equality operator:

A==B means contents of A and B compared for equivalence

Compares variables, returns 1 (true) if equivalent


InteractiveM ATLAB Numeric data logical operators Other data types

Relational/logical operators and arrays


• Logical and relational operators implicitly vectorised,
i.e., applied elementwise to conforming arrays
• Logical operators treat 0 as false (0) and any nonzero
real/complex number as true (1)
Execute the following statements & explain

>> A = -3:2, B = 2 - A
>> A > -2 % evaluates to [ 0 0 1 1 1 1 ]
>> B + 2*A > 1
>> C = abs(A);
>> test = ( C == A ) % evaluates to [ 0 0 0 1 1 1 ]
>> x = linspace(0,3,7)
>> condition1 = (x>=1) & (x<2)
>> condition2 = (x<=1) | (x>=2)
InteractiveM ATLAB Numeric data logical operators Other data types

Strings and characters


• Variables of type char are letters, digits, spaces, symbols
• A string is an array of char
• Strings are enclosed by single quotes ’
• To include single quote (’) in a string, type it twice (i.e., ’’)
• Stings can be concatenated using brackets [ ]
• Strings can be indexed using parentheses ( )

Execute the following statements & explain

>> command = ’Say ’’Open sesame!’’ next time.’


>> str1 = ’My name is ’;
>> str2 = input(’Please enter your name: ’, ’s’);
>> sentence = [ str1, str2 ] % The comma is optional
InteractiveM ATLAB Numeric data logical operators Other data types

Useful string utilities

input receives input from user


num2str converts numeric variable to string
int2str converts integer variable to string
disp displays strings to M ATLAB session
(also works for numbers/arrays directly)
fprintf formatted output to files
sprintf formatted output to strings
strcmp comparison of strings
format controls default behaviour of screen output
InteractiveM ATLAB Numeric data logical operators Other data types

Polynomials in M ATLAB
• Represented as (row) vector of coefficients of monomials
f = [5 -3 2] represents f (x) = 5x2 − 3x + 2
g = [7 2 4 -6.1] represents g(x) = 7x3 + 2x2 + 4x − 6.1
h = [4 -1 0 0] represents h(x) = 4x3 − x2
• Missing monomial terms have coefficient zero
g = [ 1 0 -3 0 0 -1 ] represents g(x) = x5 − 3x3 − 1
because g(x) = x5 + 0 x4 − 3x3 + 0 x2 + 0 x − 1

Potential confusion in using/developing software!


• Text indexes coefficients from 0, increasing powers
• M ATLAB indexes coefficients from 1, descending powers
• M ATLAB vector length n ⇒ polynomial of degree n − 1
InteractiveM ATLAB Numeric data logical operators Other data types

Utilities for polynomials in M ATLAB

poly Construct coefficient vector from roots


roots Compute roots from coefficient vector
polyval Evaluate polynomial at prescribed values
conv Polynomial multiplication (“convolution”)
deconv Polynomial division (“deconvolution”)
polyder Differentiation of polynomials
polyint Integration of polynomials

p = poly([1,2,-3]) % Polynomial p(x) with roots 1, 2, & -3


r = roots( p ) % Returns [1,2,-3] (in some order)
dp = polyder(p) % Differentiation of p(x)
P = polyint(p) % Integration of p(x)
InteractiveM ATLAB Numeric data logical operators Other data types

Heterogeneous data types

• Arrays so far all homogeneous


• M ATLAB has structures and cell arrays for heterogeneous
aggregate data
• Structures very similar to structures in C
• We will use structures later for zero-finding, quadrature,
etc.
• Cell arrays use braces { } for indexing
• See doc struct and doc cell
InteractiveM ATLAB Numeric data logical operators Other data types

Summary
• Basics of interactive computation in M ATLAB
• Arithmetic operators and order of operations
• Identifiers and reserved words
• Using mathematical functions in M ATLAB
• Documentation: help, doc, and lookfor
• Controlling/preserving output: format and diary
• Numeric variables: real and complex numbers
• Arrays: input, indexing, colon notation and operators
• standard matrix algebra operations
• vectorised operations
• scalar expansion
• Logical variables: relational and logical operators
• Other data types: char/strings, polynomials, structures,
cells

S-ar putea să vă placă și