You are on page 1of 8

Become familiar with interface:

Editor (SE) is for writing a script, which is a saved set of


instructions that can be run at the click of a button.
Script editor
Command window (CW) is for running smaller process that
doesnt save what you type, but is useful for testing snippets
Workspace of code or examining the output of your script. You can also
check the value of a variable by typing its name then enter.
Command window
Workspace (WS) is where you monitor your variables. You
can check their value and/or size if its an array.
Entering Commands:
Matlab can do basic arithmetic, although this is underutilizing it somewhat. Type 3*5 in the
CW. You should see ans = 15. This is good, but what if you wanted to use this later? Save the
output by assigning it (setting it equal) to a variable. Type m = 3*5 in the CW. You should see
m = 15 in CW and you should see the variable name and value in the WS. When assigning
values to variables, the variable name has to be on the left and the value on the right. You can
even assign a variable in terms of itself. Type m = m + 1 and you should get 16 in return. You
can also assign values to variables in terms of other variables. Type y = m/2 and y should
equal 8 in the CW. If you dont want everything to be sent to the CW, you can suppress the
output by adding a semi-colon at the end of each line you want to suppress.

Storing Data in Variables:


Variable names may contain letters and numbers, but cannot start with a number. Try to keep
variables short, and its common practice to keep single word variables all lowercase, and
especially keep the first letter lowercase. If you have a multiple word variable, there are two
general methods of naming them:
multi_word_variable = 17 where you put an underscore between each word
multiWordVariable = 17 where you capitalize the first letter of every word

Built-in Functions:
There are two parts to functions: the name and the argument. The name of a function follows the
same general rules as variable names. Every function name is followed by a set of parentheses,
which is where you enter the argument. Look at the list of commonly used Matlab functions
(credit to Dr. Brian Vick of the MechE Dept at Virginia Tech).

Arrays:
There are three common data types in Matlab: strings, scalars, and arrays. We will cover strings
later. Scalars are singular numbers, like 4, 17, or 39. Arrays are several numbers, in an array or
matrix. Use square brackets to create arrays. Type x = [3 5] and see that 3 and 5 are in the
same row. To make a new column, use a semi-colon. Type x = [3; 5] to see that 3 and 5 are in
the same row. To find the transverse of any matrix (flip it about the diagonal) just type the name
of the matrix then use an apostrophe. Type x = [3 5], then hit enter and type x and youll
see you get the same result as x = [3; 5].

For longer vectors, you can get a range by using a colon. Type y = 1:10 to get an array of all
the values from 1 to 10. A colon has a default spacing (or step size) of 1, but you can change that
by putting in two colons and declaring your step size in between the colons. Type y = 1:.5:5 to
get all the values from 1 to 5 by a step size of .5.

Array Indexing:
Sometimes you want to get only a specific bit of information from a huge array. You can specify
which elements of the array by giving the coordinates of the information. Type the name of
array, followed by parentheses with row number, comma, column number. Ex: array(3,4) gets
the item in the third row and fourth column. To grab more than one item in any direction, you
can enter an array as an argument, such as array(2:4,4) which would grab elements in the
second through fourth rows in the fourth column. If you wanted the whole row or column, enter
a colon in the argument, or if you wanted the last element enter end.

You can also change values of an array using indexing. Set an element of array to a value by
typing the elements index and assigning it a value. Ex: array(2,3) = 15.

Strings:
Scalars and arrays deal with numbers, but strings are for text. Every string is surrounded by
either a single or double quote ( or ).

Logical Statements/Operators:
In computer language, true is 1 and false is 0. You can test if two scalars or arrays are less than,
greater than, equal to (which is == by the way). More information on the second page of Matlab
functions I gave you. These are important to know, because you will use them a lot in your
conditional statements.

Conditional Statements:
(*Warning* You can get into trouble quickly with ill-defined loops. If something goes wrong,
type Ctrl+C to cancel all operations.)
There are three main types: if else statements, for loops, and while loops. If else statements work
like this:

if (something is true)
do this
elseif (something else is true)
do this instead
else
do this as a default
end

Note that I left else to send me a warning message. This is good practice when youre new to if
else statements.
For loops are loops that will perform a set of instructions for
a set number of times. For loops work like this:

for variable = start_value:stop_value


do this
end

While loops perform a set of instructions while a certain


statement is true. While loops work like this:

while (statement is true)


do this
end

Graphing/Plotting:
In general, just use the plot function.
plot(x_variable, y_variable, z_variable, colorsymbolline)

Add the z variable only if you need it, and refer to the other
pages for color, symbol, and line identifiers.

Otherwise, use hist() or surf() for histograms and 3D surface plots respectively.

When youre bored, type these into CW: why, fifteen, xpbomb
General Purpose Commands

Operators and Special Characters


+ Plus; addition operator.
- Minus; subtraction operator.
* Scalar and matrix multiplication operator.
.* Array multiplication operator.
^ Scalar and matrix exponentiation operator.
.^ Array exponentiation operator.
\ Left-division operator.
/ Right-division operator.
.\ Array left-division operator.
./ Array right-division operator.
: Colon; generates regularly spaced elements and represents an entire row or column.
( ) Parentheses; encloses function arguments and array indices; overrides precedence.
[ ] Brackets; enclosures array elements.
. Decimal point.
Ellipsis; line-continuation operator.
, Comma; separates statements and elements in a row.
; Semicolon; separates columns and suppresses display.
% Percent sign; designates a comment and specifies formatting.
_ Quote sign and transpose operator.
._ Nonconjugated transpose operator.
= Assignment (replacement) operator.

Commands for Managing a Session


clc Clears Command window.
clear Removes variables from memory.
exist Checks for existence of file or variable.
global Declares variables to be global.
help Searches for a help topic.
lookfor Searches help entries for a keyword.
quit Stops MATLAB.
who Lists current variables.
whos Lists current variables (long display).

MATLAB Commands 3
Programming

Logical and Relational Operators


== Relational operator: equal to.
~= Relational operator: not equal to.
< Relational operator: less than.
<= Relational operator: less than or equal to.
> Relational operator: greater than.
>= Relational operator: greater than or equal to.
& Logical operator: AND.
| Logical operator: OR.
~ Logical operator: NOT.
xor Logical operator: EXCLUSIVE OR.

Program Flow Control


break Terminates execution of a loop.
case Provides alternate execution paths within switch structure.
else Delineates alternate block of statements.
elseif Conditionally executes statements.
end Terminates for, while, and if statements.
error Display error messages.
for Repeats statements a specific number of times
if Executes statements conditionally.
otherwise Default part of switch statement.
return Return to the invoking function.
switch Directs program execution by comparing point with case expressions.
warning Display a warning message.
while Repeats statements an indefinite number of times.

Logical Functions
any True if any elements are nonzero.
all True if all elements are nonzero.
find Finds indices of nonzero elements.
finite True if elements are finite.
isnan True if elements are undefined.
isinf True if elements are infinite.
isempty True if matrix is empty.
isreal True if all elements are real.

MATLAB Commands 10
Vector, Matrix and Array Commands

Array Commands
cat Concatenates arrays.
find Finds indices of nonzero elements.
length Computers number of elements.
linspace Creates regularly spaced vector.
logspace Creates logarithmically spaced vector.
max Returns largest element.
min Returns smallest element.
prod Product of each column.
reshape Change size
size Computes array size.
sort Sorts each column.
sum Sums each column.

Special Matrices
eye Creates an identity matrix.
ones Creates an array of ones.
zeros Creates an array of zeros.

Matrix Arithmetic
cross Computes cross products.
dot Computes dot products.

Matrix Commands for Solving Linear Equations


det Computes determinant of an array.
inv Computes inverse of a matrix.
pinv Computes pseudoinverse of a matrix.
rank Computes rank of a matrix.
rref Computes reduced row echelon form.

MATLAB Commands 6
Plotting Commands

Basic xy Plotting Commands


axis Sets axis limits.
fplot Intelligent plotting of functions.
grid Displays gridlines.
plot Generates xy plot.
print Prints plot or saves plot to a file
title Puts text at top of plot.
xlabel Adds text label to x-axis.
ylabel Adds text label to y-axis.

Plot Enhancement Commands


axes Creates axes objects.
close Closes the current plot.
close all Closes all plots.
figure Opens a new figure window.
gtext Enables label placement by mouse.
hold Freezes current plot.
legend Legend placement by mouse.
refresh Redraws current figure window.
set Specifies properties of objects such as axes.
subplot Creates plots in subwindows.
text Places string in figure.

Specialized Plot Commands


bar Creates bar chart.
loglog Creates log-log plot.
polar Creates polar plot.
semilogx Creates semilog plot (logarithmic abscissa).
semilogy Creates semilog plot (logarithmic ordinate).
stairs Creates stairs pot.
stem Creates stem plot.

MATLAB Commands 8
Colors, Symbols and Line Types

Color Symbol Line


y yellow . point - solid
m magenta o circle : dotted
c cyan x x-mark -. dash dotted
r red + plus -- dashed
g green * star
b blue d diamond
w white v triangle (down)
k black ^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram

Three-Dimensional Plotting Commands


contour Creates contour plot.
mesh Creates three-dimensional mesh surface plot.
meshc Same as mesh with contour plot underneath.
meshz Same as mesh with vertical lines underneath.
plot3 Creates three-dimensional plots from lines and points.
surf Creates shaded three-dimensional mesh surface plot.
surfc Same as surf with contour plot underneath.
meshgrid Creates rectangular grid.
waterfall Same as mesh with mesh lines in one direction.
zlabel Adds text label to z-axis.

Histogram Functions
bar Creates a bar chart.
hist Aggregates the data into equally spaced bins.
histc Aggregates the data into unequally spaced bins.

MATLAB Commands 9

You might also like