You are on page 1of 6

MATLAB Basics L M Kalnins, February 2010

Navigation and Tools

MATLAB includes a variety of different windows for displaying different types of information and
performing specific tasks. Each window can generally be opened/closed, docked in the main window
or popped out, and repositioned/resized depending on current needs/preferences. The Window menu
helps you navigate between the currently open windows, while the Desktop menu lets you open new
windows (which can also be done from the command window).
Command Window The window where you type commands and non-graphic output is displayed.
A ‘>>’ prompt shows you the system is ready for input. The lower left hand corner of the main
window also displays ‘Ready’ or ‘Busy’ when the system is waiting or calculating. Previous
commands can be accessed using the up arrow to save typing and reduce errors. Typing a few
characters restricts this function to commands beginning with those characters.
Command History Records commands given that session and recent sessions. Can be used for
reference or to copy and paste commands.
Workspace Shows the all the variables that you have currently defined and some basic information
about each one, including its dimensions, minimum, and maximum values. The icons at the top
of the window allow you to perform various basic tasks on variables, creating, saving, deleting,
plotting, etc. Double-clicking on a variable opens it in the Variable or Array Editor. All
the variables that you’ve defined can be saved from one session to another using File>Save
Workspace As (Ctrl-S). The extension for a workspace file is .mat.
Current Directory The directory (folder) that MATLAB is currently working in. This is where
anything you save will go by default, and it will also influence what files MATLAB can see.
You won’t be able to run a script that you saved that you saved in a different directory (unless
you give the full directory path), but you can run one that’s in a sub-directory. The Current
Directory bar at the top centre of the main window lets you change directory in the usual
fashion — you can also use the UNIX commands cd and pwd to navigate through directories.
The Current Directory window shows a list of all the files in the current directory.
Editor The window where you edit m-files — the files that hold scripts and functions that you’ve
defined or are editing — and includes most standard word-processing options and keyboard
shortcuts. It can be opened by typing edit in the Command Window. Typing edit myfile will
open myfile.m for editing. Multiple files are generally opened as tabs in the same editor window,
but they can also be tiled for side by side comparison. Orange warnings and red errors appear as
underlining and as bars in the margin. Hovering over them provides more information; clicking
on the bar takes you to the relevant bit of text. Also remember that MATLAB runs the last
saved version of a file, so you have to save before any changes take effect.
Variable Editor or Array Editor Opens variables in an Excel-like format, and is useful for check-
ing what data is in which column/row, checking that value is where you meant it to be, etc. Data
can also be edited or created in this window. Double-clicking on a variable in the Workspace
will open it for editing. Multiple variables are usually opened as tabs, but can also be tiled for

1
side by side comparison.
Figure Editor MATLAB opens figures in separate windows, which includes the ability to fine-tune
the appearance of the plot, zoom, etc. You can also use the Data Cursor to extract values and
save them to the Workspace. See the Help documentation for further detail. The figures can
also be saved in a wide variety of formats — it’s usually a good idea to save them as an m-file
(File>Generate M-file) if there’s any chance at all you might want to modify the figure later
and you haven’t already saved the generating code in a m-file.
MATLAB Help MATLAB’s help documentation is very good, and can tell you pretty much any-
thing you need to know. Help>Product Help opens the Help Window, which works largely
like a web browser, including forward and back buttons. Use the Contents tab for help oriented
around a broad topic (most of what you need will be under the MATLAB heading, and then
probably Getting Starting or Graphics) — Search or Index for more specific queries (e.g. inter-
polating values, polynomial fit, etc.). The ‘see also’ at the end of each file is very useful if you
haven’t found quite the right thing. It can also suggest better ways of doing things. Typing help
commandname in the Command Window will also bring up the help file for that command.

Basic Commands and Formatting


pi, i, 2e6, Inf 3.14159..., −1, 2 × 106 , Infinity
+, -, *, / (not \) matrix addition, subtraction, multiplication, and division
+, -, .*, ./ (not .\) element-by-element addition, subtraction, multiplication, and division
xˆn xn
() Used to clarify expressions and specify order of operations when nec-
essary and to specify elements of an array. MATLAB knows the usual
rules for precedence and order of mathematical operations.
[] Used to create arrays. Not used to clarify expressions or for order of
operations.

exp(x), log(x), ex , natural log of x (base 10 log is log10(x)), x, |x|, sine of x (in radi-
sqrt(x), abs(x), ans). Use the Help window to find virtually any mathematical function
sin(x) you can think of.

variable = commands Assign a value or array to a variable name.


ans The default variable MATLAB assigns output to if you don’t specify a
variable.
command; Adding a ‘;’ to the end of a command prevents the output from being
printed onscreen, especially useful for long arrays or repetitive calcula-
tions.
function(arg1, ‘strarg’) Enclose function arguments with ‘()’ and separate with commas. Argu-
ments that are strings of characters, rather than variables or numbers,
are enclosed with ‘’.

2
[2 3 4; 5 6 7] Enter matrices with ‘[]’ brackets; separate elements of a row by spaces
or commas, and start a new row with a ‘;’.
myarray(i,j) Specifies the element in the i th row and the j th column of myarray.
Calling an element that doesn’t exist generates an error, but assigning
a value to an element that doesn’t exist simply enlarges the array. This
is a double-edged sword.
min:inc:max Generates a vector going from min to max in increments of inc. If you
don’t give inc, MATLAB assumes an increment of 1.
myarray(i:j,k) Refers to the elements in the i th to j th rows and k th column of myarray.
A ‘:’ alone specifies all the rows (or columns) of an array, ‘end’ specifies
the last row or column.
myarray(:,2) = [ ] Deletes the 2nd column of myarray. Deleting a single element produces
an error, since the result isn’t a matrix. Using only a single index, how-
ever, deletes the given element(s) and converts the remaining elements
into a row vector.

p = polyfit(x,y,n) Finds the coefficients p of the polynomial of degree n that best fits data
x, y in a least squares sense. The coefficients are given from the highest
order term to the lowest.
polyval(p,x) Returns the value of the polynomial with coefficients p evaluated at x.

Graphics Commands

Most graphics editing can also be done using the Graphics Editor in each figure window, but for
commands you will be running repeated, inclusion in scripts, etc., it is easier to specify them in the
commands. The basics are pretty self-explanatory, but most of the commands have further options
you can find in the Help documentation.

plot(x1, y1, x2, y2) Plots x1 versus y1 and x2 versus y2 on a single figure
area(x,y) Plots x versus y, but fills in the area under the curve. Useful if
your figure is trying to be a cross section.
hold on/hold off ‘Holds’ the current figure so that subsequent graphing com-
mands are added to it, rather than creating a new figure. Useful
when you want to customise each line on a plot.
... Lets you continue a command on the next line.
xlabel(‘label (units)’) Labels the x axis. Don’t forget the ‘’ around the label.
ylabel(‘label (units)’) Labels the x axis. Don’t forget the ‘’ around the label.
title(‘Plot Title’) Titles the plot. Don’t forget the ‘’ around the title.
axis([xmin xmax ymin max]) Adjusts the axes after plotting.

3
You can customise the plots almost anyway you like, but the most basic options go in a single para-
mater, ‘Linespec’, added as an additional argument to plot. It specifies:

Line Type Basic choices, such as ‘-’ for solid, ‘- -’ for dashed, ‘:’ for dotted, etc.
Marker Type Most basic shapes, such as ‘s’ for square, ‘o’ for circle, etc.
Colour A limited number that can be specified with single letters, such as ‘r’ for red, ‘c’ for cyan,
etc.

Thus plot(x,y,‘- -sc’) gives a red dashed line with red squares and plot(x,y,‘oc’) gives cyan circles with
no line.
There are also more advanced options which let you specify a wider range of colours, control the colour
of line and and marker separately, change the thickness of the line and size of the marker, etc. These
usually show up as a pair of arguments to plot, ‘ParameterName’, ‘ParameterValue’. For example,
plot(x, y, ‘- -s’, ‘MarkerFaceColor’,‘g’) turns the markers (squares, in this case), solid green. For a
wider range of colours, you have to use RGB triplets (in the range 0–1, so if you’re used to giving them
out of 255, write them as fractions [55/255 100/255 190/255], etc. RGB triplets (red-green-blue) are
a common way of specifying colours in computing, and there are charts of colours and their triplets
available online (e.g. Wikipedia Web Colours article).

Conditional Statements and Loops

If you’ve done a bit of programming, these will be familiar to you, and it’s only MATLAB’s particular
syntax that you need to learn. If you haven’t done programming before, these are statements that
enable you to write code that will be executed only under certain conditions, e.g. if x < 10 or code
that will execute repeatedly, e.g. while 0 < x < 10.

Logical Expressions

These combine statements which evaluate to either true or false (x <= 10, y == 6, etc.) with the
logical operators & (logical AND), | (logical OR), and ∼ (logical NOT). Note that when testing for
equality, you must use ==. A single = assigns the value of the right hand side to the left hand side.
If you are used to other programming languages, && and || also work (and short-circuit, which the
single forms do not).
Sample expressions:
x < 10 & y == 4 x is less than 10 and y equals 4
x + y >= 100 | x + y < 50 ∼ x == y x + y is greater than or equal to 100 or less than 50 and x
does not equal y

4
Conditional Statements

The basic conditional statement is:

if (logical expression) e.g. if x < 10 which says If x is less than 10, set
(code to evaluate if ex- b = 2x b equal to 2x . If x is
pression is true) end greater than or equal to
end 10, b won’t be assigned any
value (or will retain the
value it had before the if
statement started.
To evaluate different code for each of several possible alternatives, we have:

if (logical expression) Here, if the first expression is true, the first batch of
(code to evaluate if expres- code is evaluated, and the programme leaves the if
sion is true) block of code. If the first expression is false, it tries
elsif (2nd logical expression) the second expression, and so on. Only one batch of
(code to evaluate if 2nd ex- code is ever evaluated. You can have as many elsif
pression is true) statements as you need, and you do not have to have
..
. an else statement if no code is to be evaluated when
else all expressions are false.
(code to evaluate if no expres-
sion is true)
end
These statements can also be nested - you can put another if statement in the code to be evaluated if
a given expression is true, i.e.

if x < 10
if y < 10
b=x∗y
else
b=x+y Note that this is not a particularly sensible set of statements...
else
b=x
end

If you have different code to be evaluated when an expression is equal to certain values, i.e. you are
continually testing if x == number, there is a very similar structure called switch that you can (and
probably should) use instead.

Loops

Loops are for when you want to execute a statement a set number of times or for as long as some
expression is true. The for statement is used to evaluate code a set number of times, for example as

5
x goes from 1 to 20:

for (range of values) e.g. b=0 which Finds the sum of the
(code to evaluate for for x = 1 : 20 square from 1 to 20. The
each value) b = b + x2 b = 0 ensures that any pre-
end end vious value of b doesn’t af-
fect the result.
The while statement evaluates a block of code for as long as a given logical expression is true:

while (logical expression) e.g. x=1 which Prints the powers of 2 that
(code to evaluate while while x < 2000 are less than 2000. The
expression is true) x = 2x x = 1 starts the process off
end end correctly.

It is important to make sure that loops will eventually exit. This is particularly important with while
loops. If, for example, you forget to write the statement that changes the value of x you will be testing
the same condition ad infinitem (e.g. 1 < 10, which is always and forever true), and the loop becomes
an infinite loop. If your code mysteriously seems to run forever and ever, check for infinite loops.

You might also like