Você está na página 1de 4

CMPSC 200 Exam II Cheat Sheet

by xsgirl99 via cheatography.com/26903/cs/7655/


3 Code Categories

Definitions (cont)

if Selection Structure

Bits & Bytes

Sequences lines of code are

Flowchart- Exactly what it sounds

if comparison

The basic unit of information in

executed one after another.

like a graphical representation of

Selection Structures executes

how code flows or progresses.

some piece of code if some known

Counter- A variable that keeps

condition is true, otherwise


executes some sort of alternative
code.

computers is the bit(binary digit).

[commands to do

Can store exactly 1 logical variable

something]

Bits can only have one of two

track of some parameter of interest

end

values: 0 or 1

Array- Holds stuff. It can hold

The simplest classical selection

There are 8 bits/byte

numeric information, character

structure is the if statement.

Repetition Structures (loops)

data, symbolic data, etc. Is an

causes a group of statements to be

orderly grouping of information,

If the comparison evaluates to be

executed multiple times (either a

has no special properties by virtue

fixed number, or until some stated

of its existence.

condition is met).
Relational Operators
< less than
<= Less than or equal to
> greater than
>= greater than or equal to
== equality check
~= not equal to

Matrix-A 2D numeric array used


in linear algebra. Is used

& and (used with vectors)


| or (used with vectors)

statements are ignored.

rows=b's #of columns


b = [another matrix]

A_augmented = [A b]

programming technique that uses

thought of as multiplying the matrix

RREF_result =

vector operations instead of

by itself however many times in the

rref(A_augmented);

element by element loop-bases

exponent

solution =

Matrix must be square. Example:

RREF_result(:,end)

A4= (A)(A)(A)(A)

solution = A\b (ideal way)

operations.
Sentinel Loop- A loop that
terminates only when a specific
met
Find Command
The command find searches a

returns the index/indices of the

evaluate additional terms if you

A = [a matrix] A's #of

Raising a matrix to a power can be

xor exclusive or

evaluation. Makes sure you don't

then the do something

Code Vectorization- A

the search criteria. The command

Also called short circuit

Solving Matricies

solution = inv(A)*b

scalars)

Remember 0 is false, 1 is true

comparison evaluates to be false,

special mathematical properties!

matrix, finding what elements meet

|| short cut or (used with scalars)

statements are executed. If the

Matrix Functions

&& short cut and (used with

~ not (used with vectors or scalars)

0 and 255 for 1 byte

true, then the do something

extensively in STEM fields. Has

condition(the sentinel condition) is


Logical Operators

Power of 2: allows values between

valid results.

Syntax: A^n (requires A to be


square; compare against the

Flowcharts & Meaning

element-by-element operation

Circle/Oval - Indicates the

A.^n, where A doesnt have to be


square )

code

Matrix inverse: (A)(A-1)=1

Parallelogram - Indicates input or

(identity matrix)

output processes

A matrix inverse does not exist if

Diamond - Indicates a decision

the determinant of the matrix is

point

equal to 0; a matrix like this is

index = find(x)

known as a singular matrix

index = find(x,k) (first k

If a matrix is square and singular,

elements)

the operation M-1M would be hard

index = find(x,k,'last')

to know a priori but the result will

(last k elements)

beginning or end of a section of

be wrong.

don't need to do so.

Rectangle/Square - Indicates
calculations
if/else/elseif
if comparison % do
something
elseif comparison % do
something else

Definitions

else % do something else

Pseudocode- Verbal description

end

of code. Often is language


independent. Intermediate step
between everyday language and a
programming language.
By xsgirl99

Published 28th March, 2016.

Sponsored by Readability-Score.com

cheatography.com/xsgirl99/

Last updated 29th March, 2016.

Measure your website readability!

Page 1 of 4.

https://readability-score.com

CMPSC 200 Exam II Cheat Sheet

by xsgirl99 via cheatography.com/26903/cs/7655/


if/else/elseif (cont)

Menus

Matrix Terminology (cont)

Character Arrays (cont)

If the first statement (the if

Instead of requesting input from the

Tridigonal matrix: zero matrix

char will also accept as input the

statement) does not evaluate to

Command Window, you can have

except: for non-zero entries along

true, it checks the elseif

MATLAB collect input from a menu

the main diagonal and on the first

ASCII representation of a number,

statement(s) If nothing is true by

box.

diagonal above and below the

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
Switches have a similar purpose to
if statements.

Syntax: var =
menu('title','option
1','option 2','...')
Use in conjunction with Switches.
x=menu('S','x','y'...) if

if/elseif/else.
Often personal preference, 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
accordingly.

clock times)
Alternatives: Array operations,
find command, Code
vectorization
1. for loop - Primarily used if you
know a priori( Before the fact) how

...} (the curly braces are cell

numel counts the number of

array constructors)

elements. find only returns the

reshape command reshapes the

indices where the element that

array Syntax: reshape(A, r,c

meets that criteria is located, so we

...), reshape(A,r,[])

completing the iteration.The first

horzcatcommand

time MATLAB sees the while loop, it

count the number of elements.


Matrix Terminology
Zero matrix: matrix of zeros
Identity matrix: a matrix of zeros,
except it has 1s along the main
diagonal
Sparse Matrix: most of the
elements of the matrix have zero
elements
Dense Matrix: most of the
zero elements
Banded Matrix: non-zero elements

case 'lion shrine'

zeros or more diagonals on either

disp('I''m at the

size

(left-right) Syntax: horzcat(A1,


A2, ... )

the main diagonal and either the


diagonal above or below the main

(or can calculate it)


2. while loop - A pre-test loop: it
checks the condition before

while loop. If the condition is false,


MATLAB will never go into the while
loop. If the condition is true,

vertcat command concatenates

MATLAB proceeds into the while

vertically (up-down) Syntax:

loop.

vertcat(A1, A2, A3, ...)

3. do while loop unavailable

A = 'We are!'

in MATLAB. Guarantees one pass

B = [1 4; 3 2]

through the loop.

C = 'Penn State!'

Every for loop can be made into a

D = single([1 2; 3 4])
E = {A,B,C,D} % default printing
just shows sizes

while loop, but not every while


loop can be made into a for loop.

celldisp(E) % needed to generate

Valid for loop indexes include

display

scalars, vectors, and matrices.

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

For Loop
for some_index_variable =

Bidiagonal matrix: zero matrix


except: for non- zero entries along

many times the loop will need to run

checks to see if it should go into the

concatenates horizontally

of the cell array E

diagonal

Output:

choice. Low performance (bad

numel vs find

comprising the main diagonal and

end

store different data types within the

Syntax: mycell = {A, B, C,

switch location

disp('I''m lost')

symbolic arrays, cell arrays can

array is an array.

are confined to a diagonal band

otherwise

Unlike numeric, character or

S==2->fprintfy

location = 'lion shrine';

lion shrine')

Loops should not be your first

Cell Arrays

same array. Each element of the

elements of the matrix have non-

Switch Example

Loops

S==1->fprintfx elseif

Anything you can do with a switch


can be done using

main diagonal

letter or symbol.

Character Arrays

some_matrix

Character arrays are arrays of


characters
Key idea: The number of elements

some commands to be
executed
end

in each row has to be the same, or

I'm at the lion shrine

MATLAB will throw a warning.


By xsgirl99

Published 28th March, 2016.

Sponsored by Readability-Score.com

cheatography.com/xsgirl99/

Last updated 29th March, 2016.

Measure your website readability!

Page 2 of 4.

https://readability-score.com

CMPSC 200 Exam II Cheat Sheet

by xsgirl99 via cheatography.com/26903/cs/7655/


For Loop (cont)

Transpose Command

Numeric Data Types (cont)

Input: for k = [1 3 5 7]

Swaps rows/columns: A(i,j)

Complex Numbers- Can be

becomes A(j,i)

doubles, singles, or integers.

Character arrays must have the

Requires twice the space of the

same number of rows in every

base data types because one

column, and the same number of

needs space for both the real-

columns in every row. Cell arrays of

valued and complex- valued

chars, however, have no such

components.

restriction.

Dingle<complex # of

elseif is a case inside of an if

singles=double

selection structure; else if is a

k
end

Command (2 versions):

Output: k=1 k=3 k=5 k=7

transpose(x) or x'

Break & Continue Functions

Dot Product

Can use a break statement to

sum(A.*B) (syntactically valid)

cause the termination of the


smallest enclosing for or while
loop
Often considered bad form to use

dot(A,B) (preferred and easier to


implement)
In general, AB = B A

break without a good reason. It is


much better to write better loop
termination conditions.
Can use a continue statement to
skip the rest of the loop, advancing

Dot Product Example


A=[a 11 a 12; a 21 a 22]
B=[b 11 b 12; b 21 b 22]

to the next loop pass.

A*B=[(a 11b 11

They should not be go- to

+a 12b 21),(a 11b 12

techniques.

+a 12b 22);... (a 21b 11


+a 22b 21), (a 21b12

Timing Functions

of an else case of another if

Similar idea to cell arrays. Instead

selection structure. MATLAB

of using content indexing, however,

generally ignores white space, so

each matrix is stored is assigned a

else if is the same thing to the

location called a field (each field

interpreter as the programmer had

can be thought of like a property).


Field names are stored in order of
their creation.

good idea because it gives you an

L.nums = [1 4; 3 2]
L.myphrase2 = 'Penn State!'`

Cross Product

Short Response(Practice Exam)

and an end time

Result is a vector, always at a right

If the availability of memory is a

cputime returns CPU time (in

angle (normal, orthogonal) to the

concern, using the smallest

seconds) since you started

plane defined by the two input

necessary storage type is

vectors. Mathematically is a special

advantageous, enabling you to

case of a determinant whose first

store more things in memory. An

row comprises unit vectors. Must

example discussed in class related

contain three elements

to classic video games vs.

tic/toc can be used as


stopwatches; 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 adjustments to
the system clock, using it for timing
purposes can cause errors.

Creating a flowchart and


create a computer program is a

`L.myphrase1 = 'We are!'

comparison between a start time

timing

properly indented the code.


pseduocode before attempting to

L= We Are! [2x2] Penn State!

MATLAB; can use differences to do

(cont)

nested if selection structure inside

Structure Arrays

+a 22b 22)

clock/etime performs

Short Response(Practice Exam)

modern phone apps (where it

opportunity to think your way


through the program. A builder
wouldnt start building a house
without a blueprint; it is advisable to
think through your programs as
well.
True/False(Practice Exam)
In general, for performance
reasons it is preferable to use builtin MATLAB features such as the
find command instead of using

Numeric Data Types

seems that apps and downloads

MATLAB loops.

Double-Precision Floating-Point

are getting bigger(50 MB+)


everyday.

If MATLAB finds a true case in a

Numbers (doubles)- MATLAB


stores numeric data as doubles.
Each value requires 8 bytes of
space(64 bits).
Single-Precision Floating-Point

switch, it will NOT continue

A matrix is always 2D and has

checking the other cases.

special mathematical properties.

An exclusive or(xor) evaluates as

An array need not be 2D, has no


special mathematical properties,
and is merely a holder for data.

TRUE when either A or B (but not


both) are non-zero.

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).
By xsgirl99

Published 28th March, 2016.

Sponsored by Readability-Score.com

cheatography.com/xsgirl99/

Last updated 29th March, 2016.

Measure your website readability!

Page 3 of 4.

https://readability-score.com

CMPSC 200 Exam II Cheat Sheet

by xsgirl99 via cheatography.com/26903/cs/7655/


True/False(Practice Exam) (cont)

Potentially Useful Code

The ' operator and the transpose

num_rows = 3;

command both compute

num_cols = 4;

if grades(count) >= 90

num_pages = 2;

A_loop = A_loop + 1;

value = 46;

elseif grades(count) >=

transposes, but these two


techniques do not behave
identically under all
circumstances.

A = zeros(num_rows,

More Potentially Useful Code


(cont)

80

num_cols, num_pages); %

B_loop = B_loop + 1;

laptops, chars in MATLAB are

Optional

elseif grades(count) >=

represented by their ASCII value

for k = 1:num_pages %

when stored in memory.

loop over # of pages

For personal computers (PCs) or

In MATLAB, what would be result


of this expression: FALSE ||
(TRUE && FALSE) Answer: False
. The default numeric data type in

for i = 1:num_rows %
loop over # of rows
for j = 1:num_cols %
loop over # of cols

70
C_loop = C_loop + 1;
else
failing_loop =
failing_loop + 1;
end

MATLAB is the double.

A(i,j,k) = value;

end

Matrix multiplication is NOT

value = value - 2;

fprintf('%i A''s\n',

commutative for any square matrix.

end % cols

A_find)

end % rows

fprintf('%i B''s\n',

A matrix A is invertible if its


determinant is not equal to 0.

end % pages

B_find)

disp(A)

fprintf('%i C''s\n',
C_find)

Long Response Hints


det(A) takes the determinant of

More Potentially Useful Code

matrix A.

grades = load('P50.csv');

See Linear Algebra Section

A_find =

if rem(k,2)==0 Checks to
see if k is divisible by 2(even)

B_find =
numel(find(grades >= 80 &
grades < 90));

logspace(start,end,interva

numel(find(grades >= 70 &

end in evenly logarithmically


spaced intervals.
linspace(start,end,interva
l) Allocates numbers from start to
end in evenly linearly spaced
intervals.

failing_find)

numel(find(grades>=90));

Exam 1 Material

l) Allocates numbers from start to

fprintf('%i D''s\n',

C_find =

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;

By xsgirl99

Published 28th March, 2016.

Sponsored by Readability-Score.com

cheatography.com/xsgirl99/

Last updated 29th March, 2016.

Measure your website readability!

Page 4 of 4.

https://readability-score.com

Você também pode gostar