Show Menu

CMPSC 200 Exam II Cheat Sheet by

My Equation Sheet

3 Code Categories

Sequences – lines of code are executed one after another.
›Selection Structures – executes some piece of code if some known condition is true, otherwise executes some sort of altern­ative code. ›
Repetition Structures (loops) – causes a group of statements to be executed multiple times (either a fixed number, or until some stated condition is met).

Relational Operators

less than
Less than or equal to
greater than
greater than or equal to
equality check
not equal to

Logical Operators

and (used with vectors)
or (used with vectors)
short cut and (used with scalars)
exclusive or
not (used with vectors or scalars)
short cut or (used with scalars)
Remember 0 is false, 1 is true
Also called short circuit evalua­tion. Makes sure you don't evaluate additional terms if you don't need to do so.


Pseudocode- ›Verbal descri­ption of code. ›Often is language indepe­ndent. ›Inter­mediate step between everyday language and a progra­mming language.
Flowchart- Exactly what it sounds like – a graphical repres­ent­ation of how code flows or progre­sses.
Counter- A variable that keeps track of some parameter of interest
Array- ›Holds “stuff”. It can hold numeric inform­ation, character data, symbolic data, etc. ›Is “an orderly grouping of inform­ation”, ›has no special properties by virtue of its existence.
Matrix-A 2D numeric array used in linear algebra. Is used extens­ively in STEM fields. ›Has special mathem­atical proper­ties!
Code Vector­ization- A progra­mming technique that uses vector operations instead of element by element loop-bases operat­ions.
Sentinel Loop- A loop that terminates only when a specific condit­ion(the sentinel condition) is met

Find Command

The command
searches a matrix, finding what elements meet the search criteria.› The command returns the index/­indices of the valid results.
index = find(x)
index = find(x,k)
(first k elements)
index = find(x­,k,­'last')
(last k elements)

if Selection Structure

if comparison
[commands to do something]
The simplest “class­ical” selection structure is the
statement. ›
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.

Matrix Functions

Raising a matrix to a power can be thought of as multip­lying the matrix by itself however many times in the exponent ›
Matrix must be square. ›Example:
A4= (A)(A)­(A)(A)
Syntax: A^n (requires A to be square; compare against the elemen­t-b­y-e­lement operation
, where A doesn’t have to be square )
Matrix inverse:
(identity matrix)
A matrix inverse does not exist if the determ­inant of the matrix is equal to 0; a matrix like this is known as a singular matrix
If a matrix is square and singular, the operation M-1M would be hard to know a priori but the result will be wrong.

Bits & Bytes

The basic unit of inform­ation in computers is the bit(“b­inary digit”). ›Can store exactly 1 logical variable
Bits can only have one of two values: 0 or 1
There are 8 bits/byte ›
Power of 2: allows values between 0 and 255 for 1 byte

Solving Matricies

A = [a matrix]  A's #of rows=b's #of columns
b = [another matrix]
solution = inv(A)*b

A_augmented = [A b]
RREF_result = rref(A_augmented);
solution = RREF_result(:,end)

solution = A\b  (ideal way)


Interp­olation consists of “method[s] of constr­ucting new data points within the range of a discrete set of known data points”
› Extrap­olation consists of “the process of estima­ting, beyond the original observ­ation range, the value of a variable on the basis of its relati­onship with another variable”
Curve fitting is “the process of constr­ucting a curve, or mathem­atical function, that has the best fit to a series of data points, possibly subject to constr­aints.” Goal is to minimize the residuals: the difference between the actual and predicted values at a given point
yi = interp­1(x­,Y,xi)
. Interp­olates to find
, the interp­olated function values at the points in the vector or array
contains your known data points (functions values are
), which must be a vector, though xi can be a scalar, vector, or multid­ime­nsional array.
will always be the same size as
yi = interp­1(Y,xi)
. Same as above, except the function will assume that
x = 1:N
, where N is
(for a vector) or
(for a matrix)
yi = interp­1(x­,Y,­xi,­method)
. Same as above, except now using a method(ie cubic spline)
yi = interp­1(x­,Y,­xi,­met­hod­,'e­xtrap')
. Same as above, except used to extrap­olate beyond the data set

Flowcharts & Meaning

Circle­/Oval - Indicates the beginning or end of a section of code
Parall­elogram - Indicates input or output processes
Diamond - Indicates a decision point
Rectan­gle­/Square - Indicates calcul­ations


if comparison % do something
elseif comparison % do something else
else % do something else  end
If the first statement (the if statement) does not evaluate to true, it checks the elseif statem­ent(s) › If nothing is true by the time one gets to else, the else commands are executed
There can only be one
, there must be an
, and there can be no more than 1
You can have an
without an
, and an
without an
. However, both
are dependent on having an


Switches have a similar purpose to
›Anything you can do with a switch can be done using
Often personal prefer­ence, though you will often see switches when checking strings.
Important: In MATLAB, once a “true” case has been found MATLAB will NOT check the other cases – make sure you plan accord­ingly.

Switch Example

location = 'lion shrine';
switch location
    case 'lion shrine'
        disp('I''m at the lion shrine') 
        disp('I''m lost')
I'm at the lion shrine


Instead of requesting input from the Command Window, you can have MATLAB collect input from a menu box. ›
var = menu('­tit­le'­,'o­ption 1','option 2','...')
Use in conjun­ction with Switches.
x=menu­('S­','­x',­'y'...)  if S==1->­fpr­intfx elseif S==2->­fpr­intfy

numel vs find

counts the number of elements.
only returns the indices where the element that meets that criteria is located, so we count the number of elements.

Matrix Termin­ology

Zero matrix: matrix of zeros ›
Identity matrix: a matrix of zeros, except it has 1’s along the main diagonal
›Sparse Matrix: most of the elements of the matrix have zero elements
Dense Matrix: most of the elements of the matrix have non-zero elements
Banded Matrix: non-zero elements are confined to a diagonal band comprising the main diagonal and zeros or more diagonals on either size ›
Bidiagonal matrix: zero matrix except: for non- zero entries along the main diagonal and either the diagonal above or below the main diagonal ›
Tridigonal matrix: zero matrix except: for non-zero entries along the main diagonal and on the first diagonal above and below the main diagonal

Cell Arrays

Unlike numeric, character or symbolic arrays, cell arrays can store different data types within the same array. Each element of the array is an array.
mycell = {A, B, C, ...}
(the curly braces are cell array constr­uctors)
command reshapes the array › Syntax:
reshape(A, r,c ...)
command concat­enates horizo­ntally (left-­right) › Syntax:
horzca­t(A1, A2, ... )
command concat­enates vertically (up-down) › Syntax:
vertca­t(A1, A2, A3, ...)
A = 'We are!'
B = [1 4; 3 2]
C = 'Penn State!'
D = single([1 2; 3 4])
E = {A,B,C,D} % default printing just shows sizes
celldi­sp(E) % needed to generate display

E{end}=[ ] %will delete the last cell of the cell array E

Character Arrays

Character arrays are arrays of characters ›
Key idea: The number of elements in each row has to be the same, or MATLAB will throw a warning. › ›
will also accept as input the ASCII repres­ent­ation of a number, letter or symbol.

Curve Fitting

y = polyva­l(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 coeffi­cients in descending powers of the polynomial y. This function accepts matrix or vector x.
p = polyfi­t(x­,y,n)
. This finds the coeffi­cients of the polynomial p(x) of degree n that fits the data. p is a row vector of length n + 1 that contains the coeffi­cients of the polynomial
[p,~,mu] = polyfi­t(x­,y,n)
. Same as above except that it also returns mu, a two element vector mu=[u1, u2] where u1=mean(x) and u2=std(x)
x = fzero(­fun,x0)
tries to find a zero of the function fun near x0 if x0 is scalar

Miltiv­ariate Interp­olation

Accomp­lished using the commands
(for 2D data) or
(for 3D data)
ZI = interp­2(X­,Y,­Z,X­I,YI)
. ZI is a matrix containing elements corres­ponding to the elements of XI and YI, as determined by interp­olation within the 2D function specified by the matrices X, Y and Z. X and Y must be monotonic and have the same format ("pl­aid­") as if they were produced by meshgrid. Matrices X and Y specify the points at which the data Z is given. Out of range values are returned as


Loops should not be your first choice›. Low perfor­mance (bad “clock times”) ›
Altern­atives: ›Array operat­ions,
command, ›Code vector­ization
loop - Primarily used if you know a priori(Before the fact) how many times the loop will need to run (or can calculate it)
loop - A pre-test loop: it checks the condition before completing the iterat­ion.The first time MATLAB sees the while loop, it checks to see if it should go into the while loop. ›If the condition is false, MATLAB will never go into the while loop. If the condition is true, MATLAB proceeds into the
do while loop
– unavai­lable in MATLAB. Guarantees one pass through the loop.
loop can be made into a
loop, but not every
loop can be made into a
loop indexes include scalars, vectors, and matrices.

For Loop

for some_index_variable = some_matrix 
    some commands to be executed
Input: for k = [1 3 5 7]
Output: k=1  k=3  k=5  k=7

Break & Continue Functions

Can use a break statement to cause the termin­ation of the smallest enclosing
Often considered bad form to use break without a good reason. It is much better to write “better” loop termin­ation condit­ions.
Can use a
statement to skip the rest of the loop, advancing to the next loop pass.
They should not be “go- to” techni­ques.

Timing Functions

performs comparison between a start time and an end time
returns CPU time (in seconds) since you started MATLAB; can use differ­ences to do timing
can be used as stopwa­tches; the time difference is in seconds (best way)
Issues with trying to time runs: Run times can vary from run to run depending on available RAM. Also, the OS can make adjust­ments to the system clock, using it for timing purposes can cause errors.

Transpose Command

Swaps rows/c­olumns:
Command (2 versions):

Dot Product

(synta­cti­cally valid) ›
(preferred and easier to implement)
In general,

Dot Product Example

A=[a11 a12; a21 a22]
B=[b11 b12; b21 b22]
A*B=[(a11b11 +a12b21),(a11b12 +a12b22);... (a21b11 +a22b21), (a21b12 +a22b22)

Cross Product

Result is a vector, always at a right angle (normal, orthog­onal) to the plane defined by the two input vectors. Mathem­ati­cally is a special case of a determ­inant whose first row comprises unit vectors. ›Must contain three elements

Numeric Data Types

Double­-Pr­ecision Floati­ng-­Point Numbers (doubles)- ›MATLAB stores numeric data as doubles. Each value requires 8 bytes of space(64 bits). ›
Single­-Pr­ecision Floati­ng-­Point Numbers (singles)- Uses half the storage space of a double, implies that they have half the storage. Each value requires 4 bytes of space(32 bits). ›
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-v­alued and complex- valued compon­ents.
Dingle­<co­mplex # of single­s=d­ouble

Structure Arrays

Similar idea to cell arrays. Instead of using content indexing, however, each matrix is stored is assigned a location called a field (each field can be thought of like a property).
Field names are stored in order of their creation.
`L.myp­hrase1 = 'We are!'
L.nums = [1 4; 3 2]
L.myph­rase2 = 'Penn State!'`
L= We Are! [2x2] Penn State!

Numerical Integr­ation

. Takes a function between limits a and b and numerical integrates it to within a default error of 1e-6 using a recursive adaptive Simpson quadrature
. Same as above, except you can specify the accuracy needed with
. Same choices available as above, except it also returns the number of function evalua­tions
Z = trapz(Y)
. Y is the vector repres­enting the function whose integral you want to approx­imate.
Z = trapz(X,Y)
. Same as above, except that the integr­ation will be done with respect a variable
operates virtually the same as
, except that it will return the cumulative sums

Differ­ential Equations

When specifying a deriva­tive, use the symbol D (
). nth order deriva­tive: specify n after the symbol D (4th order derivative for y:
will result in the family of solutions to the DE with respect to the default variable
will result in the family of solutions to the DE with respect to the symbolic variable
dsolve­(eq­uat­ion­,co­ndi­tio­n1,­con­dit­ion2, …, condit­ionN, symvar)
will result in the family of solutions to the DE equation using the initial or boundary conditions
condit­ion1, condit­ion2, … conditionN
(condi­tions are written as equati­ons), with respect to the
(if you just want the default,
, then omit the
dsolve­(eq­uat­ion­1,e­qua­tion2, … equationN, condit­ion1, condit­ion2, … condit­ionN, symvar)
will result in the family of solutions to the DEs
equation1, equation2, …, equationN
using initial or boundary conditions
condit­ion1, condit­ion2, … , conditionN
with respect to the symbolic variable
solves ordinary differ­ential equations

Short Respon­se(­Pra­ctice Exam)

If the availa­bility of memory is a concern, using the smallest necessary storage type is advant­ageous, enabling you to store more things in memory. An example discussed in class related to “classic” video games vs. modern phone apps (where it seems that apps and downloads are getting bigger(50 MB+) everyday.
A matrix is always 2D and has special mathem­atical proper­ties. An array need not be 2D, has no special mathem­atical proper­ties, and is merely a “holder” for data.
Character arrays must have the same number of rows in every column, and the same number of columns in every row. Cell arrays of
, however, have no such restri­ction.
is a case inside of an
selection structure;
else if
is a nested
selection structure inside of an
case of another
selection structure. MATLAB generally ignores white space, so
else if
is the same thing to the interp­reter as the programmer had properly indented the code.
Creating a flowchart and pseduocode before attempting to create a computer program is a good idea because it gives you an opport­unity to think your way through the program. A builder wouldn’t start building a house without a blueprint; it is advisable to think through your programs as well.

True/F­als­e(P­ractice Exam)

In general, for perfor­mance reasons it is preferable to use built-in MATLAB features such as the
command instead of using MATLAB loops.
If MATLAB finds a true case in a switch, it will NOT continue checking the other cases.
An exclusive or(
) evaluates as TRUE when either A or B (but not both) are non-zero.
The ' operator and the transpose command both compute transp­oses, but these two techniques do not behave identi­cally under all circum­sta­nces.
For personal computers (PCs) or laptops, chars in MATLAB are repres­ented by their ASCII value when stored in memory.
In MATLAB, what would be result of this expres­sion:
Answer: False
. The default numeric data type in MATLAB is the double.
Matrix multip­lic­ation is NOT commut­ative for any square matrix.
A matrix A is invertible if its determ­inant is not equal to 0.

Long Response Hints

takes the determ­inant of matrix A.
See Linear Algebra Section
if rem(k,­2)==0
Checks to see if k is divisible by 2(even)

Exam 1 Material

Allocates numbers from start to end in evenly logari­thm­ically spaced intervals.
Allocates numbers from start to end in evenly linearly spaced intervals.

Potent­ially Useful Code

num_rows = 3;
num_cols = 4;
num_pages = 2;
value = 46;
A = zeros(num_rows, num_cols, num_pages); % Optional
for k = 1:num_pages % loop over # of pages
   for i = 1:num_rows % loop over # of rows
     for j = 1:num_cols % loop over # of cols
        A(i,j,k) = value;
        value = value - 2;
      end % cols
   end % rows
end % pages

More Potent­ially Useful Code

grades = load('P50.csv');
A_find = numel(find(grades>=90));
B_find = numel(find(grades >= 80 & grades < 90));
C_find = numel(find(grades >= 70 & grades < 80));
failing_find = numel(find(grades < 70));
[num_rows, ~] = size(grades); 
count = 0;
A_loop = 0; B_loop = 0; C_loop = 0; failing_loop = 0;
while count < num_rows
 count = count + 1;
 if grades(count) >= 90
 A_loop = A_loop + 1;
 elseif grades(count) >= 80
 B_loop = B_loop + 1;
 elseif grades(count) >= 70
 C_loop = C_loop + 1;
 failing_loop = failing_loop + 1;
fprintf('%i A''s\n', A_find)
fprintf('%i B''s\n', B_find)
fprintf('%i C''s\n', C_find)
fprintf('%i D''s\n', failing_find)


calculates the symbolic single integral of a symbolic function F with respect to the default indepe­ndent variable
calculates the symbolic single integral of the symbolic function F with respect to the symbolic variable symvar
evaluates the results of the integral over the symbolic or numeric range [a, b] of the indepe­ndent variable
calculates the symbolic single integral of a symbolic function F with respect to the symbolic variable symvar; evaluates the results of the integral over the symbolic or numeric range [a, b] of the indepe­ndent variable
symvar has to be in single quotes if the variable does not already exist as a symbolic variab­le(same for differ­ent­ials)


calculates the symbolic first derivative of a symbolic function F with respect to the default indepe­ndent variable
calculates the symbolic first derivative of a symbolic function F with respect to the symbolic variable symvar (symvar has to be in single quotes if the variable does not already exist as a symbolic variable)
calculates the symbolic nth derivative of the symbolic function F with respect to the default indepe­ndent variable
calculates the symbolic nth derivative of the symbolic function F with respect to the symvar

Advanced Graphics

command creates a pseudo­color checke­rboard plot
MATLAB generally recognizes three different techniques for storing and repres­enting images: ›1. Intensity Images (“gray scale”) ›2. Indexed Images ›3. RGB (“true color”) images
intensity image can be created with the
Can adjust the colormap of an image with the
Can check image properties with the
Can read in image data using
. ›Code:
X = imread­('l­igh­tho­use.jpg') imagesc(X)
imwrit­e(a­rra­yname, colormap, 'filen­­rmat')
manually saves an image. Four possible fields: ›
: name of the MATLAB array in which the data is stored.
: the name of your colormap, if applic­able.
: the name you want to use to store the data›.
is the file extension
causes figure windows and their children to update, and flushes the system event queue
h = animat­edl­ine()
creates an animated line without data, adding it to the current axis. Can use a loop to later add data points. Can also use the


Hey, I am in CMPSC 200 class and I used your cheatsheet to do well and to pass midterm 2. I am graduating this semester and I have a job lined up but I need to get a C in this class. So, I was wondering if you are going to make a cheatsheet for final. The sole reason I passed midterm 2 is because of your cheatsheet. I would really appreciate it if you can make one for final.

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          More Cheat Sheets by xsgirl99