CMPSC 200 Final Exam PSU
pause(#)
# second pause, will show grid lines and then after # seconds will go away
Block comment
%{..........%} - must put writing on the next line from the first percent
Root finding
- "zero" of a function - syntax: x = fzero(fun, x0) fzero tries to find a zero of the function fun near x0 if x0 is scalar. fun is called the function handle. fzero returns NaN if the search for a sign change fails. if x0 is a vector of length 2, fzero will assume that the sign of fun(x0(1)) differs from the sign of fun(x0(2))
Digression: Taylor Series
- a Taylor series is a series expansion of a function f(x) about a given point alpha - a special case, known as Maclaurin series, of the Taylor series exists when alpha = 0
Handle graphics
- a handle is a name given to a MATLAB object
Determinants
- a matrix inverse does not exist if the determinant of the matrix is equal to zero - a matrix whose determinant is equal to zero is knows as a singular matrix - det(A) = det(a b c d) = |a b c d| = ad-bc
Polar fplot
- can convert from polar coordinates to cartesian coordinates via the coordinate transformation x = r cos(theta) and y = r sin(theta) - interval domain is now actually for the implicit variable - not that x and y are also symbolic variables
Continue
- can use continue statement to skip the rest of the loop, advancing to the next loop pass - may not use continue statements for a grade in this class
State-space (s/m/d system
- consider a spring-mass-damper system given by mx + cx + kx = f(t)
ezcontour
- contour plot - contour
fimplicit3
- implicit 3D plot - no direct analog
Matrix used for plotting
- in the foregoing examples, if we looked at the data that we had, the first data point z(1,1) was in the bottom left hand corner of the matrix. intuitively, this makes sense, considering where the origin of a graph is located
Loops
- not your first choice - low performance - many good alternatives: array operations, find command, code vectorization
Matrix powers
- raising a matrix to a power can be through of as multiplying the matrix by itself however many times in the exponent - matrix must be square
Create script
- where we are going to store commands - they do not execute they are simply stored - working in a script allows you to save your work
fmesh
- wireframe mesh - mesh
Audio data file types
.au, .snd - audio .wav - microsoft wave file
The algorithmic process to obtain this matrix is known as
Gauss-Jordon. it makes use of elementary row operations, there are three types - interchanging ("swapping") the position of two rows - multiplying a row by a non-zero scalar - adding or subtracting a scalar multiple
NaN
IEEE representation for "not a number":
inf
IEEE representation for infinity
MATLAB stands for
Matrix laboratory
String data
a character array ( spaces do not count as characters
Array
a container for multiple pieces of information
Flowcharts
a flowchart is exactly what it sounds like, a graphical representation of how code flows or progresses oval - indicated the beginning or end of a section of code parallelogram - indicated input or output processes rhombus - indicated a decision point rectangle - indicated calculations
Computer
a programmable electronic device that can store, retrieve, and process data
Program
a set of instructions to perform specific tasks
Algorithm
a set step for "doing something"
Character data
a single character (each element required 2 bytes of space: 2 bytes * 8 bits/byte = 16 bits
Error
a statement that will display in the command window and the will stop the code execution entirely (red color)
Warning
a statement that will display in the command window to warn the programmer of an issue (orange color)
By doing .* it gives you
an element by element operation
MATLAB cannot respond to a termination command while
an input statement is pending
angle(my_complex)
angle ("phase") (rads) of complex numbers
You can put a matrix into
another matrix
CPU has two main components
arithmetic and logic unit (ALU) - mathematical operations control unit - fetches the next instruction, decodes the instruction, and then executes the instruction as appropriate
= means
assignment/equal to
Every for loop can be made into a while loop,
but not every while loop can be made into a for loop
numden
can be used to find the numerator and denominator of an expression syntax: num1 = numden(z)
meshgrid
can map a vector into a 2D array - meshgrid (x,y)
Subplot
can plot multiple plots in one figure syntax: subplot(m,n,p) m = number of rows for entire figure n = number of columns for entire figure p = plot number, reading across the rows
tic/toc
can use tic and toc as stopwatches; once again, the time difference is in seconds
Repetition structures
causes a group of statement to be executed multiple times (loops)
CPU
central processing unit
rem(x,#)
check if x is divisible by the number
clc
clear the command window
To delete specific variables type
clear(variable)
clf
clears the content of a figure
Clock
clock commands gives the current time - doesn't account for leap seconds, daylight savings time adjustments, or differences in time zones
close all
closes all of the figures
close
closes the current figure
Compiled
code written by the programmer is reduced to a set of machine-specific instructions prior to runtime. these instructions are saved as executable files, which can be run
interpreted
code written by the programmer is saved in the same format as it was originally written in, which is converted to machine-specific instructions at runtime
collect
collects like terms x = collect(equation)
pwd
command to show you where to store a file
nargout('x')
determines the number of output arguments. when used with a user-defined function, it determines how many output arguments were requested by the user
Scope of this course
development and implementation of algorithms in a procedure oriented language, with emphasis on numerical methods for engineering problems
exp(x)
e^x
High-level languages
easy for humans to understand, but too difficult for a computer to understand
Monotonic
entirely non-increasing or non-decreasing
etime
etime performs comparison between a start time and an end time
time interval
ex: from 1-10 in steps on 0.75 t = [1;0.75;10]
Selection structures
executes some piece of code if some known condition is true, otherwise executes some sort of alternative code (can be many branches)
Machine language
generally quite difficult for humans to understand, the binary digits that contain instructions that can be understood by the computer
histogram(z)
histogram
help
huge list of help - must type in command window
atan2(my_complex), real(my_complex)
imaginary and real component of the complex number
Break and continue statements may look useful but
in general, they should not be "go-to" techniques - one useful use for these is "error trapping"
When nesting for loops the
inner counter resets every time the loop is re-initialized
Output
input inputted or processed through the program is output to the user
Plotting example
input: t = 1:3; y =exp(t) plot(t,y) output: t = 1 2 3 y = 2.7183 7.3891 20.0855
atan2(#)
inverse tangent of x
isreal(X)
is it real, true or false
X = isprime(#)
is the number prime - 1 is true - 0 is false
For the main program to be able to call the function
it must be saved in the same file directory as the main portion of the code itself
Add a counter to
keep track of many times the while loop has executed, and terminate once one has reached the desired number of iterations
title(' ')
know as latex
length(data#)
largest # of elements in any dimensions
realmax
largest possible floating point number
inmax
largest possible integer
Sequences
lines of code are executed one after another
loglog(a,b)
log(a) and log(b)
semilogx(a,b)
log(a), normal b on the x axis
comet(x,y)
makes an animation
Zero matrix
matrix of zeros
Dense matrix
most of the elements of the matrix have zero elements
Sparse Matrix
most of the elements of the matrix have zero elements
expand
multiplies out all of the parts of the expression or equation syntax: x = expand(equation)
function[ output_args ] =
name (input)
Relational operators
one can perform comparisons between the relationships between scalars or vectors using the relational operators below 0 = false 1 = true < - less than <= - less than or equal to > - greater than >= - greater than or equal to == - equality check ~= - not equal to
contour( )
plots a 2D representation of 3D surfaces
mesh(z) and mesh(x,y,z)
plots a 3D mesh
surf( )
plots a 3D surface
For the code to run, the function must be
saved in the folder MATLAB is looking into
[rows#, cols#] =size(data#)
size of the data set
size(data#)
size of the data set - the first number will be the number of rows and the second number will be the number of columns
inmin
smallest possible integer
sortrows(data#, #)
sort rows based on the # column
sort(data#, 'descend')
sort the data in descending order
Transpose
swaps rows and columns syntax: transpose(x)
Processing
the computer is instructed what to do you the program, often using information that was input to the program
AND
the element of the output array is set to 1 if both input arrays contain a non-zero elements at the same array index; otherwise the element is set to 0 ex: A & B, or and(A,B)
X = primes(#)
to get all prime factors up to the number
[a,b] = ginput(n)
uses n points
vari(data#)
variance (square of the standard deviation)
uiimport('title_of_file.m')
will pull up an import wizard with the variables
doc( )
will pull up the definition of things
Interpolation
methods of constructing new data points within the range of a discrete set of known data points - some interpolation techniques are excellent, yielding useful results
Four key parts to a function
name, inputs, outputs, comments that describe the other parts
log
natural log
Banded matrix
non-zero elements are confined to a diagonal band comprising the main diagonal and zeros or more diagonals on either side
randn(#)
normally distributed pseudo random number
Default degrees for MATLAB is
radians
rem(x,y)
remainder of x divided by y
cputime
returns CPU time (in seconds) since you started MATLAB - can use differences to track timing - do not recommend for timing operations
X = floor(#)
round in the direction of the nearest integer towards negative infinity
X = round(#)
round to the nearest integer
realmin
smallest possible floating number
Specialized algorithms exist to
solve systems of equations under certain special conditions. Specialized techniques, for example, exist for sparse matrix systems, banded matrix systems. In general, specialized techniques tend to outperform the traditional Gaussian elimination-based techniques one would have seen in linear algebra. Sometimes, these specialized methods can outperform Gaussian elimination by several orders of magnitude
X = fix(#)
truncation function - chops off the decimal place
grid on
turn on a cartesian grid that corresponds with the axes
grid off
turns the grid off
How to pass information to functions?
value - a copy of the variable is sent to the function. if you want to update the original variable, you would have to overwrite it with the new value returned from the function reference - the memory address itself of a variable is sent to the function, allowing the programmer to directly update the variable itself, even if the variable originally had local scope elsewhere
Creating a menu
var - menu ('title', 'option 1', 'option 2', '..')
mean(data#)
will find the mean of the data set
transpose(data#)
will return the original data#
sprintf
works in a similar manner as the fprintf command, instead of sending results to the command window, it assigns the result a variable name
dlmwrite
write matrix to ASCII-delimited file
Middle Riemann sum
x*i=12(xi+xi-1)for all i: S - approximates the function by its value at the middle point of the subinterval, yielding multiple rectangles with a base of delta x and the average height between the left and right - the resulting area for the n-1 subintervals k = 1, 2, 3, ..., n yields an approximate area A=b-ank=1nf(xk-1+xk2) - this technique tents to be -on average- a bit more robust than either the left or right Riemann sums
Implement
- code the program - test the program
Analyze
- specify what the program needs to do - develop the algorithm(s) to solve your problem - verify that what you have will work
Maintain the code
for large or long-term software systems, this can be the most expensive part
Low-level languages
harder for humans to understand, but easier for a computer to convert to usable instructions
nthroot(#,#)
nth root (x,n)
magnitude = abs(my_complex)
only works for complex numbers
X = ceil(x)
round in the direction of the nearest integer towards positive infinity
std(data#)
sample standard deviation
std(data#, 0)
sample standard deviation
sign(#)
signum function - if the input is positive MATLAB will return the number +1 - if the input is negative MATLAB will return the number -1 - if the input is zero MATLAB will return the number 0
eps
smallest number that you can perform an operation with
rand(#)
uniformly distributed pseudo random numbers
fix(clock)
version of clock that is easier to read
median(data#)
will find the median of the data set
mode(data#)
will find the mode of the data set
prod(data#)
will find the product of the data set
sum(data#)
will find the sum of the data set
Forward difference
(dydx)i=yi+1-yixi+1-xi, but note you will be missing the last point. For the sample code, in its place insert a NaN so that the matrices are dimensionally consistent. This a common technique in MATLAB since a lot of built-in functions ignore NaN when they encounter it
Backward difference
(dydx)i=yi-yi-1xi-xi-1, but note you will be missing the first point. For the sample code, in its place insert a NaN so that the matrices are dimensionally consistent. This is a common technique in MATLAB since a lot of built-in functions ignore NaN when they encounter it
Type field formats
- %f - fixed-point notation - %e - exponential notation - %d - decimal notation. does not include trailing zeros if number is an integer. if number includes a fractional component, it is displayed using exponential notation - %i - integer notation - %g - the short of: %f or %e - %c - character information (one character at a time) - %s - string of characters (displays entire string)
fplot
- 2D plot - plot
fplot3
- 3D plot - plot3
Double-precision floating-point numbers (doubles)
- MATLAB by default stores numeric data as doubles - each value required 8 bytes * 8 nits/byte = 64 bits
Images types & built-in images
- MATLAB generally recognizes three different techniques for storing and representing images: - intensity images ("gray scale") - indexed images - RGC ("true color") images - some built-in images are available in the language, including flute, duper, detail, mandrill, clown, spine, cape, earth, gatlin, ...
Symbolic Data
- MATLAB has a symbolic toolbox that uses symbolic data to perform symbolic algebraic operation - one method of accomplishing this is with the sims command syntax: syms x y
Symbolic Engine
- MATLAB's computer algebra system (CAS) prior to the late 2000's was powered by MAPLE - Symbolic engine then transitioned to MuPad: utilizing research done at the university of Panderborn, MuPad was originally produced by SciFace software, MuPad was bought by MathWorks and discontinued as a stand-alone product - MuPad itself will at some point no longer be available in MATLAB. MathWorks is further developing their "own" proprietary MATLAB symbolic engine
Format command
- \n: linefeed (new line) - \r: carriage return - \t: tab - \b: backspace
A matrix
- a 2D numeric array used in linear algebra - is used extensively in STEM fields - has special mathematical properties
Computer function
- a piece of computer code that accepts an input argument from the user and provides output to the program - convenience: particularly if you have something that needs to be done multiple times in a piece of code - maintainability: easier to segment your code into rational pieces that are easier to maintain
While loop
- a pre-test loop: it checks the condition before completing the iteration - the first time MATLAB sees the while loop, it checks to see if it should go into the while loop: if the condition evaluates to false, MATLAB will never to into the while loop; if the condition evaluates to true, MATLAB proceeds into the while loop - once one has gotten into the while loop, MATLAB will proceed with the next iteration: if the condition evaluates to true, MATLAB will proceed with the next iteration; if the condition evaluates to false, MATLAB will jump to the next statement after the end of the while loop
Numerical solutions to ODEs
- a stiff equation is a DE where some numerical solution approaches are "numerally unstable" unless you see extremely small step sizes. There is a lot of fascinating research into stiff Des, but at a glance this means that solving these systems typically requires a different or specialized approach - two approaches: could use anonymous functions, but usually easier to just use a programmer-defined function - if you have a DE of 2nd order or higher, you must convert these to an equivalent system of first order DEs
Curve fitting
- a useful function when we talk about curve-fitting is polyval - y = polyval(p, x) returns the value of the polynomial y of degree n evaluated at x. the input argument p is a vector of length n+1 whose elements are the coefficients in descending powers of the polynomial y. this ruction accepts matrix or vector x - can be accomplished with the ploy fit function. be careful: do not try to over-fit your polynomial, it is Weill-known statistically that if you select a polynomial of too high degree that quirky things can happen
Row echelon form means that
- all nonzero rows are above any rows that contain all zeros - the first nonzero number from the left of a nonzero row is always to the right of the pivot of the row above it
Backslash operator
- an alternative to calculating the matrix inverse it is unique to MATLAB - When one uses the \ operator, MATLAB automatically examines the matrix system to determine which specialized algorithm to use to most efficiently solve the matrix system
Indexing for loops with matrices
- instead of indexing a for loop with a matrix, you have the option of using a matrix as the index - these are not used too often, but can be useful, particularly if you want to vectorize your code
Intensity images
- an example of an intensity image can be created with the imagesc command - sample code: imagesc(peaks) - image colors are determined by a colormap - great if the colors are not required to a priori mean something specific - can adjust the colormap of an image with the colormap command - sample code: load flujet imagesc(X) colormap(cool) - for the built-in images, there are built-in colormaps available - one could also define their own custom colormap - sample code: load flujet imagesc(X) colormap(map)
State-space (3rd ode)
- another example: assume we have an equation of the form - Ay + By + Cy + Dy = f(t) - where A, B< C, D are constants - dependent variable: y - highest derivative: 3 - 1 state x 3 derivates = 3 equations
Simpson's rule
- approximates the function by fitting parabolas under the curve - important quirk: must use an even number of intervals - it is more computationally expensive than trapezoid's but it is a better fit at time
Trapezoidal rule
- approximates the function by fitting trapezoids underneath the curve with a heights of h = b-a/N-1 - recall the area of a trapezoid is A=1/2h(b1+b2) - the resulting area for the n-1 subintervals yields an approximate area
Four possible fields
- arrayname: name of the MATLAB array in which the data is stored - colormap: the name of your colormap, if applicable - filename: the name you want to use to store the data - format is the file extension
Character arrays
- arrays of characters - key idea: the number of elements in each row has to be the same, or MATLAB will throw a warning - remember: MATLAB is converting the letter ASCII representations in memory - can get around this using a command called char - char will also happily accept as input the ASCII representation of a number, letter or symbol - num2str will preserve spacing - can convert a character value to a numeric value with the command str2num
Matrix used for images
- by contrast, matrices that represent images typically start in the top left hand corner - we have two commands available to work with images: image and imagesc (image with scaling)
transparency
- by default, MATLAB surfaces render with an opaque color scheme. this is fine for many graphics, but can sometimes obscure details - we can set the transparency with the alpha command. a transparency value of 1 results in opaque, while 0 is transparent
Hidden lines
- by default, when MATLAB mesh plots are created, any part of the surface that is not obscured is just not drawn; this typically makes the plot easier to interpret - this attribute is controlled using a command called hidden. if you do not specify the property, hidden on is implied to be used, alternatively, you can manually specify hidden off to turn off this feature
Selection structures: if/elseif/else
- can also use else if and else as choices - take the following form: if comparison [ commands to do something ] else if comparison [ commands to do something else ] else [ commands to do something different ] end - if the first statement does not evaluate to true, it checks else if statement(s) - if nothing is true by the time one gets to else, the else commands are executed - there can only be one if, there must be an end, can be no more than one else
Logical operators
- can augment performing comparisons using "and", "not", "or" & - and (used with vectors) | - or (used with vectors) ~ - not (used with vectors or scalars) xor - exclusive or && - short cut an (used with scalars) | | - short cut or (used with scalars)
Multivariate interpolation
- can be accomplished using the commands interp2 (for 2D data) or interp3 (for 3D data) - syntax: - ZI = interp2(X, Y, Z, XI, YI) ZI is a matrix containing elements corresponding to the elements of XI and YI, as determined by interpolation within the 2D function specified by the matrices X, Y, and X. X and Y must be monotonic - ZI = interp2(Z, XI, YI) same as above, except it assumes a default grid of sample points X = 1:n and Y = 1:m where [m,n] = size(Z) ZI = interp2(X, Y, Z, XI, YI, method) same as above except now using a method specified ZI = interp2(..., methodical, extrapaal) same as above except used to extrapolate beyond the data set
Univariate interpolation
- can be accomplished with the interplay command - syntax: -yi = interpl(x, Y, xi) interpolates to find yi, the interpolated function values at the points in the vector or array xi. x contains your known data points, which must be a vector, though xi can be scalar, or vector, or multidimensional array. yi will always be the same size as xi - yi = interpl(Y,xi) same as above, except the function will assume that x = 1:N, where N is length(Y) (for a vector) or size (Y, 1) for a matrix - yi = interpl(x, Y, xi, method) same as above, except now using a method - yi = interpl(x, Y, xu, method, 'extra') same as above, except used to extrapolated beyond the data set
Matrix multiplication
- can be thought of as a series of dot products - only defined if inner dimensions match; result size is the outer dimensions
Cell array
- can store different data types within the same array - each element of the array is an array syntax: mycel = {A, B, C, ...} - indexing system for cell arrays is the same as that used in other arrays - E {3} prints all of cell 3 - E {1} (1,2) prints 1st row, 2nd column of the cell with "multilayer indexing" - E {2} (:) transforms cell 2 into a column vector - can create a graphical represetaioc with the command cellplot - it is possible to delete cells - it is also possible to appendix cells together
Break
- can use a break statement to cause the termination of the smallest enclosing for or while loop - it is often considered very bad form to use break without a really good reason for doing so - may not use break statements for a grade in this class
pcolor
- can use the pcolor command to create a pseudo color checkerboard plot - a pseudocolor checkerboard is a rectangular array of cells - colors can be specified - looks like a bird's eye view of the mountains, one can also have manually rotated the plot to achieve a similar view - could apply shading as well; default result is shading faceted - code: pcolor(peaks)
Boolean (logical) data
- can use the words true and false when programming (easier to remember than 0's and 1's)
Riemann Sums
- consider a function f on the interval I = [a,b] - possible to examine the function over discrete n-1 subintervals - choosing different xi* produces different Riemann sums and therefore different integral approximations - if you average the left and right Riemann sum, you get the trapezoidal sum - while we do not have to, let us consider for simplicity the case where we have partitions of equal size. each of these subintervals then has a length delta x and is found via delta x = b-a/n
Cubic spline
- correct for this flaw by ensuring that at the data points, the adjacent splines have the same 0th, 1st, and 2nd derivatives - a cubic spline S(x) placed through the data points (x1, y1) through (xn, yn) is given by a set of cubic polynomials
Shading flat
- could remove the lines on the plot by specifying a different shading - notice that the large positive values of z are yellow, and large negative values of z are dark blue - code: pcolor(peaks) shading flat
Substitution via subs
- creating and manipulating symbols is all well and good, but sometimes need to perform substation as well, MATLAB gives you the option of substituting numbers, symbols, or other variable names - if you substitute a known symbol or a numeric value, no special formatting is needed
Linear curve fitting
- curve fitting is the process of constructing a curve, or mathematical function, that has the best fit to a series of data points, possibly subject to constraints - like we saw with linear interpolation, the easiest approach would be to fit a linear equation of the form f(x) = ax+b - our goal with curve fitting is to minimize the residuals: the difference between the actual and predicted values at a given point
Symbolic calculus and functions
- default symbolic variables: for many operations, you can specify what the variable of interest is. if you do not specify the variable of interest, MATLAB uses a default selection: the variable closest to the letter "x" in the alphabet
differentiation
- derivative: instantaneous rate of change; an analogous word is differential - analogy and syntax: univariate derivative: instantaneous rate of change or the slope of a lie multivariate derivative: a partial derivative is a derivative of a function with respect to 1 variable, keeping the other variables constant, various versions of multivariate differentiations exist, such as the gradient or the curl
Do While loops
- does not exist in MATLAB - behaves like a while loop, except one is guaranteed a first pass through the loop no matter what happens to the condition later on. The primary differences that the do while loop - when it is available in a language - is a post-test loop; the loop test does not occur until the interpreter has already done one iteration of the loop, so one is guaranteed to always get at least one iteration out of the loop
Structure arrays
- each matrix is stored and assigned a location called a field (each field can be thought of like a property) - can check the field names in use with the following fieldnames: M = fieldnames(x) - it is possible to reorder fields - it is possible to delete fields
State-space decomposition
- every ODE can be decomposed into a system of first order differential equations - for the numerical built-in ODE solution techniques we will examine, you will need to simultaneous first order differential equations - this is sometimes known as a "state-space" approach - the number of first order equations will be equal to the sum of number of independent variables times the order - these are best illustrated by example
Main idea
- every character stored in memory has a binary representation and a binary representation and a binary equivalent - when you convert from a character to a numeric data type you get the numeric equivalent in
3 types of loops
- for loop - while loop - do while loop (unavailable in MATLAB)
Beware with the example for ODE's
- forgetting to consistently name the function file the same thing - forgetting that MATLAB needs to see the function file in the folder it is looking in
Number display
- format short: 4 decimal digits - format long: 15 decimal digits - format short e: 4 decimal digits scientific notation - format long e: 15 decimal digits scientific notation - format bank: 2 decimal digits real numbers only - format short eng: 4 decimal digits engineering notation - format long eng: 14 decimal digits engineering notation - format rat: fraction form - format short g: MATLAB selects best - format long g: MATLAB selects best
Animatedline - creates a line animation
- h = animatedline creates an animated line without data, adding it to the current axis. you can use a loop to later add data points - h = animatedline(x,y) creates an animated line with initial data points x and y - h = animatedline(x,y,z) is the same as above except the initial data points are x, y, and z - h = animatedline(..., Name, Value) uses any of the argues from above except that you can also specify animated line properties; for more about what is available, see the help or doc pages - you can use the addpoints command to add the data
An array
- holds "stuff": it can hold numeric information, character data, symbolic data, etc. - is "an orderly grouping of information" - has no special properties by virtue of its existence
Images
- image data is stored in MATLAB using matrices
fimplicit
- implicit 2D plot - no direct analog
Numerical integration
- in general, if you want to use left-point Riemann sums, right-point Riemann sums, or mid-point Riemann sums, you will have to take the form described in Lecture 25 and code them up as algorithms - A couple special built-in cases exist - q = integral(function, a, b) takes a function from between limits a and b and numerical integrates it to within a default error - q = integral(function, a, b, Name, Value) same as above, except you can specify absolute ('AbsTol') or relative ('RelTol') tolerance requirements - the function should generally be written so that it can perform array operation
Different syntax's for find command
- index = find(x) - index = find(x,k) - index = find(x, k, 'last') - [row, col] = find(x, ...S)
Complex numbers (can be doubles, singles, or integers)
- requires twice the space of the base data types because one needs space for both the real-values and complex-values components
Indexed images
- instead of the matrix representing a list of intensity values, the matrix with an indexed image is a list of colors - this technique, which is useful when the color of a picture is important, is similar to the "paint by number" concept - each element of the matrix contains a number that corresponds to a color - you can make your own colormaps or you can use the built-in options - GIFs are usually indexed images - ex: load earth image(X) colormap(map) axis image
Integration
- integral: "anti-derivative" in effect, one performs the opposite calculation as differentiation. this can be thought of loosely as "reverse differentiation" - analogy and syntax: single integral: the integral represents the area under the curve and above the x-axis high order integrals exist - so-cakked "multiple integrals" - and can be calculated as "integrals of integers"
Advantages/disadvantages of global variables
- it is visible to all parts of the code - it is modifiable by all parts of the code
Which technique is best?
- left-point and right-point sums were just wrong. In practice, they are not used as often because of this - the others all got the correct answer. the choice between these depends on what the data looks like and what computational expense you can tolerate
Parametric fplot
- loosely speaking, parametric equations are those that are a function of a different variable - one of the more common is to have functions of time
Interactive curve fitting
- need to create a plot first with a discrete data point - to activate the curve-fitting tools, select tools -> basic fitting from the menu bar in the figure. the basic fitting window should open on top of your plot
Reading/Writing image files
- now that we have a high-level understanding of images, it would be prudent to circle back and dig a little bit deeper on issues of reading and writing such files - can use the interactive import wizard - for most standard image formats, the imread command is a good approach - for other formats it can be easiest to use the load function - you can manually save an image the same way you ca save a figure: file -> save as... - you can also save it with the imwrite command - syntax: imwrite(arrayname, 'filename.format') or imwrite(array name, colormap, filename.format')
ODE solver - types of problems - approach - notes
- ode45 - non-stiff DEs - Runge-Kutta: uses an explicit Runge-Kutta (4,5) formula called the Dormant-Prince pair - this is your Swiss-army knife solver; should typically be your first choice approach (unless you know a priori special properties about the system) single step solver - ode23 - non-stiff DEs - Runge-Kutta; uses an explicit Runge-Kutta (2,3) pair of Bogacki and Shampine - if the function is "mildly stiff," this solver might be a better approach than ode45. single step solver - ode113 - non-stiff DEs - Adams - multi-step solver - ode15s - stiff DEs and differential algebraic equations - numerical differentiation formulas (NDFs) or backwards differentiation formulas (BDFs) - often difficult to predict which technique will work best on stiff DEs - ode23s - stiff DEs -Rosenbrock - modified second order Rosenbrock formulation - ode23t - moderately still DEs and differential algebraic equations - Trapezoid rule - useful if you want a solution without numerical dampening - ode23tb - stiff DEs - TR-BDF2 - uses an implicit Runge-Kutta formula with the trapezoid rule (TR) and a second order backwards differentiation formula (BDF2) - ode15i - fully implicit DEs - BDF - used to solve implicit DEs that are of the form f(y,y',t)=0
Integer (whole numbers)
- often used to count, or as matrix/array indexes - storage depends on if the integer is signed or unsigned: signed integers yield more storage space but also require more space - if a non-integer number is stored as an integer, it is rounded then stood
Plot properties
- one can get a list of properties with the get command - sample code (assuming the plot on the pervious slide has already been created): get(h1)
Performance "guiding principles"
- only print using print statements: it takes quite a bit of time to print all of your calculation results to the screen - MATLAB has to stop calculations to print, so only print what you need - if you know how big a result vector will be from a loop, consider pre-allocating a vector of that same size - potentially with the zeros, one, or NaN commands - consider feedback from the MATLAB GUI - both the profiler and the run and time features - because of quirks with OSs, it is often beneficial to run code multiple times to get average run times
syntax: polyfit
- p = polyfit(x, y, n) this finds the coefficients of the polynomial p(x) of degree n that fits that data. p is a row vector of length n+1 that contains the coefficients of the following polynomial p(x) = p1x^n+p2x^n-1+...+pnx+pn+1 [p, ~, mu] = polyfit(x, y, n) same as above except that it also returns mu, a two element vector mu = [mu1, mu2] where mu1 = mean(x) and this centering and scaling transformation improves the numerical properties of both the polynomial and the fitting algorithm. NOTE: this also returns a structure array S, but S is not of interest to us at this point. We decline to store it in memory by replacing the variable name with ~ instead - special case: you know a prior that your regression line should pass through zero. we had previously talked about how the | operator can be used to solve linear algebra problems. you can also use it to solve least squared problems - in this case, it will yield the results that have the best ("least amount of") least squared error
Symbolic plotting: fplot
- plotting is also available for symbolic expressions - historically, "ez" plots were suggested; the new approach consists of the "f" plotting commands - the simplest of these commands is fplot: default range is from -5 to 5, but can be customized: determined how many points to use automatically; can add titles, aces labels, etc as usual
Numerical integration
- recall that an integral can be thought of as the area underneath a curve - we can use geometry to approximate the areas underneath curves
Spare Arrays/Matrices
- recall that sparse arrays/matrices are arrays/matrices that are sparsely populated - we can use the sparse command: -- if we store a matrix using doubles, it takes 8n bytes, where n represents the number of elements in the matrix -- the amount of memory saved is a function of how spare the matrix is - for a 1000 x 1000 identity matrix, the result has a size of 16,004 bytes = 0.016004 MB
Steps for pseudocode
- request character string input from user - print the string to the screen - MATLAB code: str = input('Enter strig:', 's') disp(str)
Cross product (vector product)
- result is a vector, always at a right angle to the plane defined by the two input vectors - mathematically is a special case of a determinant whose first row comprises unit vectors - inputs must contain three elements - syntax: C = cross(A,B)
Numerical differentiation caution
- results from numerical differentiation of "noisy" discrete functions are typically even "noisier," they also can be unreliable. In other words, numerical differentiation tends to amplify noise in the data - techniques have been studied to deal with this, but they are beyond the scope of this cause - for our purposes: we will assume our functions of interest are not very "noisy"
Movies
- same idea as before, except now you store the frames, and then you play the frames as a movie - key commands: getframe or getframe(h): gets the movie frame if applicable, from object h - movie - plays the movie. a couple different versions to note: - movie(M) plays the movie in M once - movie(M,n) is the same as above, except the movie will play n times. if n is negative, each cycle is shown forward then backwards. If n is a vector, the first element is the number of times to play the movie, and the remaining elements make up a list of frames to play in the movie - movie(M, n, fps) is the same as above, except MATLAB plays the movie at fps frames per second; the default is 12 frames per second. generally speaking, you can ask MATLAB to play a movie faster than the computer can render it, so try not to make your movies run too fast - movie(h, ..) plays the movie centered in the figure or axes identified by the handle h; you then have all of the choices in the three options above to choose from
Figure properties
- same ideas as plot properties - sample code: get(h2)
Shading interp
- since the data in the figure is represented by a matrix, would it not make sense to have some control over such a matrix? - code: pcolor(peaks) shading interp
Getting image information
- sometimes, you will be presented with an image and want to know additional information about the image - one can check this with the imfinfo command - sample code: my_info = imfinfo('lighthouse.jpg') - one can then read in the data from the image using the mired and imagesc commands - sample code: X = imread('lighthouse.jpg') imagesx(X)
Dot product syntax
- sum(A.*B) - sdot(A,B)
fsurf
- surface plot - surf
Switches
- switches have a similar purpose to if statement - anything you can do with a switch can be done using if/elseif/else - once a "true case" has been found MATLAB will NOT check the other cases ex: switch var case option otherwise end - can have as many "case" as you need but only one "otherwise"
Substitution via symfun
- symfun creates a symbolic function; can use the result to evaluate different inputs
Manipulating Axes
- syntax: set(h, 'PropertyName', 'PropertyValue', ...)
Data Types
- the basic unit of information in computers is the bit: bits can only have one of 2 values: 0 or 1, bit is a portmanteau (blending) of the phrase "binary digit" - one of the more commonly discussed units of information in computers is the byte: typically is expressed as 8 bits/byte, power of 2: allows for values between 0 and 255 for 1 byte
Reshaping arrays: cat
- the cat command concatenates input arrays along a given dimension dim syntax: cat(dim, A1, A2, A3,...)
Difference equations and numerical differentiation
- the command diff can also be used to calculate the differences between points. we can then use these differences to calculate the slopes
Simplify
- the command simplify is used to simplify expressions or equations using built-in simplification rules - a useful command often used in conjunction with simplify is pretty - note: there formerly was a simple command in MATLAB that has a similar purpose; as of recent MATLAB versions, that command no longer exists
The following must match identically for a function
- the functions name - the name of the function that you call in the script - the name of the function in the function header
RGB Images
- the last technique for storing image data in a 3D array of dimension m x n x 3. a color is listed on a page - consider our lighthouse data from before - again, you can read in the image with imread and image commands
Reduced row echelon form
- the pivot value is identically equal to 1 - the pivot value can be the only nonzero entry in its column syntax: reef(A)
Selection structures: if
- the simplest "classical" selection structure is the if statement - takes the following form: if comparison [ commands to do something ] end - if the comparison evaluates to be true, then the "do something" statements are executed - if the comparison evaluates to be false, then the "do something" statements are ignored
Lighting
- there are a fair amount of built-in lighting features by the key one to know is camlight. there are a couple different versions of note for this command - camlight('headlight') creates a light at the camera position - camlight('right') creates a light right and up from the camera. camlight(without arguments) does the same thing as this version - camlight('left') creates a light left and up from the camera - camlight(az, el) lets you specify the light at an azimuth as and elevation el with respect to the camera position. the camera target is in the center of rotation, and az and el are in degrees - camlight(..., 'style') allows you to specify the lighting style. the default 'local' though you also have an option 'infinite' which models a light source located at infinity
Numerical solutions to ODEs
- there are many ways to solve differential equations. we will talk about two of them - Euler's method - runge-kutta methods
Annotation Axes
- there is a 4th layer present on each plot - this layer is transparent, and is used to insert annotation objects such as lines, legends, and text boxes onto a figure. one approach is to use the annotation command
Declaring symbols: syms
- to declare MATLAB symbols, we can use the sims command - syntax: sums variable1 variable2 - creates a variable without assigning a numeric or character value to it - Note: as you can see, sometimes CASs do not return results in a form that you are accustomed to mathematically. assuming that there were no problems entering your expressions these should be mathematically equivalent
Animation
- two main approaches to this in MATLAB: redrawing and easing
Redrawing and easing
- typical approach is to loop over something that is changing and update the drawing as you go - set - can use set to modify various properties - drawn - creates the animation. drawn causes figure windows and their children to update, and flushes windows and their children to update, and flushes the system event que. any callbacks generated by incoming events, these are dealt with before drawn returns. other options are available, see help or doc
trapz
- use the trapezoidal method to fit trapezoids under the curve as an approximation of the area - key idea: you want to operate on the data itself, not a function. a couple variants of interest exist: - Z = trapz(Y) Y is the vector representing the function whose integral you want to approximate. if Y is a matrix, trap will return a row vector with the integral over each column. if Y is a multi-dimensional array, traps will operate on the first non-singleton dimensions; note that a singleton dimensions is a dimension whose size is 1. default is for unit spacing, but if you want spacing other than that, you can multiply Z by the spacing increment of interest - Z = trapz(X, Y) same as above, except that the integration will be done with respect to a variable X
Single-precision floating-point numbers (single)
- uses half the storage space of a double - therefore they have half the storage - each value requires 4 bytes of space: 4 byes * 8 bits/byte = 32 bits
Infinite loops
- usually caused by faulty logic; they tend not to occur too often with for loops, but are a common error with while loops - the loop doesn't have to continue infinitely - all the loop really has to do is to continue ad nauseam (at least longer than you want it to)
Pseudocode
- verbal description of code - often is language independent - intermediate step between everyday language and a programming languages
Spline interpolation
- we saw earlier that linear interpolations, while relatively easy to perform, might not be the best "go-to" solution if one requires relatively high accuracy - uses different polynomial between each pair of discrete points - if you just used linear splines, you would end up with splines that lacked "smoothness"
solve (symbolic root-finding)
- when applied to an expression, MATLAB will assume that the expression would be set equal to 0 when symbolically determining the roots of the expression - when applied to an equation, MATLAB solves the equation symbolically. Note the syntax where = = is used instead of =. the syntax = is only used for assignment - to store the result of the line MATLAB tried to solve for x if there is an x in the expression, otherwise MATLAB will solve for the variable closest to x - if you would prefer to specify the variable to solve for, you can do so - solve can also be used to solve systems of linear or non-linear equation - in general, if you can use linear algebra techniques. it is preferable that one does so, but remember the you cannot solve higher-order systems with linear algebra
Figure handles
- you can assign a figure to have a name; this makes it easier to work with, and provides you with a unique figure identifier syntax: h2 = figure(1)
Plot Handles
- you can assign a plot to have a name: this makes it easier to work with, and provides you with a unique plot identifier
Axis handles
- you can assign an axis to have a name; this makes it easier to work with, and provides you with a unique axis identifier
Numeric Data Types
-doubles - singles complex numbers - integer
Movie data file types
.avi - audio/visual interleaved file .mpg - motion picture experts group
Common file types
.cdf - common data format
Scientific data file types
.fits - flexible image transport system data
Format data file type
.hdf - hierarchical data format
Text files
.mat - MATLAB workspace .dat - ASCII data .txt - ASCII Data .csv - comma-separated values ASCII data
Image data file types
.tiff - tagged image file format .bmp - bit map .jpeg or jpg - joint photographics expert group .gif - graphics interchange format
Data file type
.wkl - Lotus 123
Spreadsheet file type
.xlx, .xlxs - excel spreadsheet
Write to files with fprintf is a three step process
1. open (or create) a file 2. write to the file 3. close the file
bar(x)
2D bar graph (vertical by default)
barh(x)
2D horiztonal bar graph
pie(y)
2D pie chart
bar3(x)
3D bar graph (vertical by default)
bar3h(x)
3D horizontal bar graph
plot3(x,y,z)
3D line plot
pie3(y)
3D pie chart
Six ways to allocate matrices
A = [ 1 2; 3 4 ] A = [ 1, 2, 3, 4 ] A = [ 1 2 3 4 ] A = [ 1, 2; 3, 4 ] A = [ 1, 2; 3, 4 ] A = [ 1 2; 3 4 ]
Three phases of program writing
Analyze, implement, maintain the code
Central difference
Central difference: (dydx)i=y+1-yi-1xi+1-xi-1, but note that you will be missing the derivatives at the first and last points. The easiest way to work with this technique is to use the gradient command. Syntax: dy_dx = gradient(y, x); if x is omitted, will assume the points are evenly spaced with a step size of 1
OR
Remember that this symbol is the pipe(|), not an L. The element of the output array is set to 1 if either input arrays contains a non-zero element at the same array index; otherwise the element is set to 0. ex: A | B, or (A,B)
Two main classes of errors
Syntax - "is it written validly?" - the code is written in such a way that the interpreter or compiler does not understand what you have asked it to do, and so it is unable to execute your code Logic - "does it do the correct thing?" - code is valid syntax, but does not accomplish what you wanted it to do - MATLAB cannot recognize these on their own, and you can only find them through code inspection, hand calculations, etc - these are the most dangerous errors, because they are the easiest to miss
EXCLUSIVE OR
The element of the output array is set to 1 when either A or B (but not both) are nonzero. In other words, the result is false when both A and B are zero or when both A and B are nonzero. ex: xor(A,B)
Rationale
Why does it pay to know how to manipulate expressions by hand? - many STEM courses evaluate you on how you think - never trust anything that comes to of a computer Why bother? - scientific expressions can become unwieldy to work with by hand - humans are mistake prone: careless, absent-minded, easily distracted, bad handwriting
To terminate code while its its running, select
Windows: control-C (at the same time) Mac: command-period (at the same time)
Function
a mathematical relationship that maps an input to an output
Identity matrix
a matrix of zeros, except it has 1's along the Amin diagonal
Counters
a variable that keeps track of some parameter of interest two main types - how many? - how much? you can have as many counters as you need; if you want to track different events, you can simply use different counter variables
Constant
a variable whose value is not intended to change
Create a toolbox
a way to save functions so MATLAB looks for them when you call them - command is pathtool
type
a way to view information about some built-in MATLAB functions ex: type polar
abs(data#)
absolute value
Operating systems
allocated computer resources and allows communication between the user and the computer
Function plot
allows you to plot a given function without calculating the given x-axis and y-axis values syntax: plot('fctn', [a,b])
Global scope
are available in other parts of the code if made available within a function - have limited purpose - for this class, can only use global variables for physical constants; a convention one often sees is to write constants in capital letters
disp(x)
command to print the contents of a variable without its label
== means
comparison for equality
my_complex = # + #i
complex numbers
Reshapping arrays: horzcat
concatenates horizontally (left-right) syntax: horzcat(A1, A2, ...)
Reshaping arrays: vertcat
concatenates vertically syntax: C = vertical(A,B)
Polynomial curve fitting
conducted similarly to the process that we had for linear curve fitting, except that instead of using the linear equation f(x) = ax+b we will use a polynomial of the form
A variable can
contain multiple pieces of information
Width field
controls the minimum number of characters to be printed restriction: the width must be a positive decimal integer
X =rats(#)
converts input into a fraction
num2str
converts numbers to a character array; disp requires that all of the things to display are in the same "data type" ex: disp(['The values in x are: ', num2str(x) ])
X = complex(#,#)
create a complex number (real, imaginary)
sphere
create a unit sphere
magic(n)
creates a "magic" matrix; constructed from the integers 1 thought n^2 with equal row and column sums. n must be a scalar greater than or equal to 3
figure(1)
creates a figure numbered 1
figure(2)
creates a figure numbered 2
ones(m) and ones(m,n)
creates a matrix of ones
zeros(m) and zeros(m,n)
creates a matrix of zeros - rows, columns
cumprod(data#)
cumulative product of the data set
cumsum(data#)
cumulative sum of the data set
date
current date (day month year)
clock
current time (year month day hour min sec)
input
data from the user is entered into the computer
histogram(z,#)
data, number of bin (lines on the bar graph)
global my_constant
declares my_constant to have a global variable
clear
delete all the variables from the workspace
nargin('x')
determines the number of input arguments, when used with a user-defined function, it determines how many input arguments were actually entered
syntax: diff
diff(f) - calculates the symbolic first derivative of a symbolic function f with respect to the default independent variable diff(f, var) - calculates the symbolic first derivative of a symbolic function f with respect to the symbolic variable var diff(f, n) - calculates the symbolic nth derivative of the symbolic function f with respect to the default independent variable diff(f, var, n) or diff(f, n, var) - calculates the symbolic nth derivative of the symbolic function f with respect to the symbolic variable var
You can manipulate a while loop into behaving like a
do while loop by influencing the loop condition on the first iterations
rows1 = NN1(#)
extract first element of NN1
cols1 = NN1(#)
extract the second element of NN1
diag(A)
extracts the diagonal of a 2D matrix
X = factorial(#)
factorial
factor
factors the expression syntax: x = factor(equation)
RC
first position row and second position is column
fliplr(A)
flips a matrix into its mirror image, from left to right
flipud(A)
flips a matrix vertically
fprintf
formatted print functions. you can - specify the format of the number to be printed - skip to a new line, insert tab, and do other special things with spacing on the screen - use fprintf to print to files (instead of the screen) - general form of the command: fprintf (format-string, var, ...)
How can one find the minimum of a function?
from calculus, we know we take its derivative and look to see where it is zero; this gives us the extrema (extreme points of the function)
The "Big O" notation indicated
higher order terms (H.O.T.s)
Truth tables
often encountered in formal studies in logic, a truth table is a table of true and false values based on the input argument(s). For the two argument logical operators (AND, OR, and EXCLUSIVE), one may construct a truth table for the various possible combinations of Boolean input arguments
pause
paused until user presses a key
Non-volatile memory
permanent storage, information persists even after power is lost. typically slower than volatile memory ex: read-only memory (ROM), compact discs (CD), magnetic tape
std(data#, 1)
population standard deviation
Precision field
preceded by the period (.), specifies the number of decimal places after the decimal point for both fixed point and exponential numbers
for loop
primarily used if you know a priori how many times the loop will need to run basic syntax: for some_index_variable = some_matrix some commands to be executed end - loop is executed once for each element in the index matrix - a common index choice is k
load('title_of_file.m')
programmatically reads data and it is stored in automatically
sort(data#)
sort the data set from lowest to highest number
sortrows(data#)
sort the rows based on the 1st column
sqrt(#)
square root
Run and time
suggests performance improvements
Matrix inverse
syntax: a = [ matrix ] x = inv(a)
Reshapping arrays: rehsape
syntax: reshape(A, r, c, ...), reshape(A, r, ..., [ ])
Numerical differentiation
take the limit as delta x approaches 0 of f(x + delta x) - f(x) / delta x - to determine how accurate this is, we need to use Taylor series
Volatile memory
temporary storage, information is lost when the power to the memory is lost. typically faster or higher performing than non-volatile memory ex: RAM, DRAM (dynamic ram)
find
the command find searches for a matrix, finding what elements meet the search criteria. the command returns the index/indicies of the valid results
NOT
the element and the output array is set to 1 if the input array contains a 0 value element at the same array location; otherwise, the element of the output array is set to 0 if the input array is non-zero. As one can see, when NOT is used true becomes false, and false becomes true, ex: ~A or not(A)
scope
the extent of the area or subject matter that something deals with or to which it is relevant
High-level computer architecture
the main memory stores programs and program data in random access memory (RAM)
extrapolation
the process of estimating, beyond the original observation range, the value of a variable on the basis of its relationship with another variable - more often than not, extrapolation can be a fool's errand: one must assume the data will behave like it had been behaving, which is not always a safe bet
Short-circuit evalution
the second operand is evaluated iff ("if and only if") the result is not fully determined by the first operand. In other words, based on the definitions listen above if the second input argument would not change the outcome of the operator, it is ignored. If one knows one condition is more likely to trigger something to happen in their code than the other, it makes sense from an efficiency standpoint to list that condition first. Short-circuit evaluation can only be done with scalars, and is supported by the scalar-only operators && (compare against & above) and | | (compare against | above)
Categorizing code
there are three categories of categorizing code - sequences - selection structures - repetition structures
Analyze code
this report displays potential errors and problems, as well as opportunities to improve your MATLAB programs
X = gcd(#,#)
to get greatest common denominator
X = sinh(#)
to get hyperbolic sin (exponential)
X = asinh(#)
to get inverse hyperbolic sin
X = asin(#)
to get inverse sin(#)
X = lcm(#,#)
to get least common multiple
X = factor(#)
to get prime factors
X = sind(#)
to get sin(#) in degrees
X = sin(#)
to get sin(x)
Can use a plot as a "sanity check"
to make sure results look reasonable
numel(data#)
total number of elements
Left Riemann sum
x*i=xi-1for all i: S - approximates the function by its value at the left-end point, yielding multiple rectangles with a base od delta x and a height of f(a+ideltax) - the resulting area for the n-1 subintervals I = 0, 1, 2,..., n-1 yields an approximate area A=x[f(a)+f(a+x)+f(a+2x)+...+f(b-x)] - this technique tends to: overestimate f if f is monotonically decreasing on the interval of interest; underestimate f if f is monotonically decreasing on the interval of interest
Right Riemann sum
x*i=xifor all i: S - approximates the function by its value at the right-end point, yielding multiple rectangles with a base of delta x and a height of f(a + ideltax) - the resulting area for the n-1 subintervals I = 0, 1, 2,.., n yields an approximate area A=x[f(a)+f(a+x)+f(a+2x)+...+f(b)] - this technique tends to: underestimate f if f is monotonically decreasing on the interval of interest; overestimate f if f is monotonically increasing on the interval of interest
To store a variable x as a 64-bit signed integer
y = int64(x)
Bidiagonal matrix
zero matrix except for non-zero entires along the main diagonal and either the diagonal above or below the main diagonal
Tridiagongal matrix
zero matrix except for non-zero entries along the main diagonal and on the first diagonal above and below the main diagonal