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)
xor 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 find 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]
end ›
The simplest “class­ical” selection structure is the if 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 A.^n, where A doesn’t have to be square )
Matrix inverse: (A)(A-1)=1 (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 yi, the interp­olated function values at the points in the vector or array xi. x contains your known data points (functions values are Y), which must be a vector, though xi can be a scalar, vector, or multid­ime­nsional array. yi will always be the same size as xi
yi = interp­1(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 = 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 if, there must be an end, and there can be no more than 1 else.
You can have an else without an elseif, and an elseif without an else. However, both else and elseif are dependent on having an if.


Switches have a similar purpose to if statem­ents.
›Anything you can do with a switch can be done using if/els­eif­/else.
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. ›
Syntax: 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

numel counts the number of elements. find 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.
Syntax: mycell = {A, B, C, ...} (the curly braces are cell array constr­uctors)
reshape command reshapes the array › Syntax: reshape(A, r,c ...), reshap­e(A­,r,[])
horzcatcommand concat­enates horizo­ntally (left-­right) › Syntax: horzca­t(A1, A2, ... )
vertcat 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. › ›
char 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). fzero tries to find a zero of the function fun near x0 if x0 is scalar

Miltiv­ariate Interp­olation

Accomp­lished using the commands interp2 (for 2D data) or interp3 (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 NaNs


Loops should not be your first choice›. Low perfor­mance (bad “clock times”) ›
Altern­atives: ›Array operat­ions, ›find command, ›Code vector­ization
1. for loop - Primarily used if you know a priori(Before the fact) how many times the loop will need to run (or can calculate it)
2. while 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 while loop.
3. do while loop – unavai­lable in MATLAB. Guarantees one pass through the loop.
Every for loop can be made into a while loop, but not every while loop can be made into a for loop.
Valid for 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 for or while loop
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 continue statement to skip the rest of the loop, advancing to the next loop pass.
They should not be “go- to” techni­ques.

Timing Functions

clock/­etime performs comparison between a start time and an end time
cputime returns CPU time (in seconds) since you started MATLAB; can use differ­ences to do timing
tic/toc 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: A(i,j) becomes A(j,i)
Command (2 versions): transp­ose(x) or x'

Dot Product

sum(A.*B) (synta­cti­cally valid) ›
dot(A,B) (preferred and easier to implement)
In general, AB ≠ BA

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

q=quad­(fu­nct­ion­,a,b). 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
q=quad­(fu­nct­ion­,a,­b,tol). Same as above, except you can specify the accuracy needed with tol.
[q,NFE­]=q­uad­(...). 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 X
cumtrapz operates virtually the same as trapz, except that it will return the cumulative sums

Differ­ential Equations

When specifying a deriva­tive, use the symbol D (Dy). nth order deriva­tive: specify n after the symbol D (4th order derivative for y: D4y)
dsolve­(eq­uation) will result in the family of solutions to the DE with respect to the default variable
dsolve­(eq­uat­ion­,sy­mvar) will result in the family of solutions to the DE with respect to the symbolic variable symvar
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 symvar (if you just want the default, t, then omit the symvar)
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
ode45 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 chars, however, have no such restri­ction.
elseif is a case inside of an if selection structure; else if is a nested if selection structure inside of an else case of another if 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 find 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(xor) 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: FALSE || (TRUE && FALSE) 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

det(A) 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

logspa­ce(­sta­rt,­end­,in­terval) Allocates numbers from start to end in evenly logari­thm­ically spaced intervals.
linspa­ce(­sta­rt,­end­,in­terval) 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)


int(f) calculates the symbolic single integral of a symbolic function F with respect to the default indepe­ndent variable
int(f,­symvar) calculates the symbolic single integral of the symbolic function F with respect to the symbolic variable symvar
int(f,a,b) evaluates the results of the integral over the symbolic or numeric range [a, b] of the indepe­ndent variable
int(f,­sym­var­,a,b) 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)


diff(f) calculates the symbolic first derivative of a symbolic function F with respect to the default indepe­ndent variable
diff(f­,sy­mvar) 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)
diff(f,n) calculates the symbolic nth derivative of the symbolic function F with respect to the default indepe­ndent variable
diff(f­,sy­mvar,n) or diff(f­,n,­symvar) calculates the symbolic nth derivative of the symbolic function F with respect to the symvar

Advanced Graphics

pcolor 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 imagesc command
Can adjust the colormap of an image with the colormap() command
Can check image properties with the imfinf­o('­ima­ge.j­pg') command
Can read in image data using imread and imagesc. ›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: ›arrayname: name of the MATLAB array in which the data is stored. colormap: the name of your colormap, if applic­able. filename: the name you want to use to store the data›. format is the file extension
set(h,­'Pr­ope­rty­Nam­e',­Pro­per­tyV­alu­e,...) where h=plot­(x,y)
drawnow 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 addpoints command.


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