Getting started on Matlab
Running Matlab
To run Matlab on your own computer, follow the instructions of the official website. No worries though if you don't have a Matlab license at hand. You can:
- either run it on one of Stanford's computers (e.g. in libraries)
- or connect remotely to the University's computing environment.
In the latter case, here is the procedure:
- Open a terminal window (
Terminal
on Mac/Linux andPuTTY
or equivalent on Windows) - Access the cluster via the command
ssh your-sunetid@rice.stanford.edu
- Enter your SUNet password and choose your favorite 2FA method when prompted
- Run Matlab with the commands
module load matlab
matlab
This is it, you are now ready to use Matlab!
Getting started
Basic operations
Here are the basic operations you can perform.
Type | Command | Example | Result |
---|---|---|---|
Addition | + |
3 + 3 |
6 |
Subtraction | - |
3 - 3 |
0 |
Multiplication | * |
3 * 3 |
9 |
Division | / |
3/3 |
1 |
Exponentiation | ^ |
3^3 |
27 |
You have to be careful about the way you combine multiple operations one after another. Formulas are evaluated from left to right, and exponentiation has priority over multiplication and division, which have priority over addition and subtraction.
Also, use =
to assign a value to a variable.
Built-in functions
Trigonometry
Here are some useful functions to tackle problems involving angles:
Type | Command | Example | Result |
---|---|---|---|
Sine | sin |
sin(pi/4) |
0.7071 |
Cosine | cos |
cos(pi/4) |
0.7071 |
Tangent | tan |
tan(pi/4) |
1.0000 |
Please note that Matlab uses radian units by default. To switch to degrees, just add the letter d
at the end of the above functions: cosd
, sind
, tand
.
Exponentials and square root
Other main mathematical functions have a pretty standard notation on Matlab.
Type | Command | Example | Result |
---|---|---|---|
Exponential | exp |
exp(2) |
7.3891 |
Logarithm | log |
log(2) |
0.6931 |
Square root | sqrt |
sqrt(2) |
1.4142 |
Rounding and remainder
It can be useful to take advantage of the following functions as well.
Type | Command | Example | Result |
---|---|---|---|
Floor | floor |
floor(3.4) |
3 |
Ceil | ceil |
ceil(3.4) |
4 |
Round | round |
round(3.4) |
3 |
Modulo | mod |
mod(10, 4) |
2 |
Vectors
Syntax
Numbers inside a vector are delimited by brackets and separated by spaces for the case of a row vector (e.g. [1 2 3 4 5]
) and by the ;
character for a column vector (e.g. [1 ; 2 ; 3 ; 4 ; 5]
).
Quick generation
There are two ways to generate vectors that have a starting and an ending point:
- If you know the increment you want to impose, you can use the
::
notation.
x = 0:0.01:1
Here, the example will provide a vector of numbers ranging from 0
to 1
by increment of 0.01
.
- If instead, you wish to specify the number of values to generate, use the
linspace
function.
x = linspace(0, 1, 100)
The above example will output a vector of 100
numbers evenly spaced from 0
to 1
.
Common operations
- Adding elements to a vector is convenient. Suppose variable
a
has the value[1 2]
. The command
[a 3]
will give you [1 2 3]
and
[a [3 4]]
will output [1 2 3 4]
.
-
Also, it is possible to transpose a vector
a
with the commandtranspose(a)
ora.'
-
To select values with respect to a condition, you only have to put the condition based on which values are selected in the index.
x = [1 2 3 4 5]
x(sin(x) > 0.5)
-
Element-wise operations are often times very useful. An element-wise operation is indicated by a dot (
.
): exponentiation of a vectoru
by a vectorv
is writtenu.^v
, multiplication isu.*v
and divisionu./v
. -
You can easily convert a vector to a matrix with the
reshape
command. For example,
x = 1:10
reshape(x, [2,5])
converts the 10-long row vector x
into a matrix with 2 rows and 5 columns.
- Also, you can sum and multiply all elements of a vector
u
, by typingsum(u)
andprod(u)
respectively.
Matrices
Syntax
Matrices are written row by row. For example, a matrix with 3 rows and 2 columns can be input like the following
[1 2;
4 5;
6 7]
Quick generation
Characteristic matrices can be generated with one-liners too. For a 3 by 2 matrix filled with zeros, use zeros(3, 2)
and ones(3, 2)
if you want it to be filled with ones.
Common operations
-
Operations for vectors still hold here. Please also note that when used without a dot, the multiplication symbol
*
denotes matrix multiplication. -
You can flatten an array
A
to a vector with the commandA(:)
. -
The linear system
A*x = b
can be solved forx
via the commandA\b
.
Writing your functions
Simple case
It can be handy to use functions, especially if we wish to repeat a given calculation multiple times. Below is a simple function of two variables.
some_function = @(x, y) 3*x.*y
For example some_function(1, 2)
will output 6
.
Note that we used the element-wise operation .*
so that this function can be applied on vectors, too.
Advanced case
Sometimes, you may need to compute results of functions that cannot be written in a simple way.
In that situation, you have to create a .m
file in your current directory, and name it the way you would like your function to be called (here the name of the file would be some_function.m
).
Then, you are free to write the operations that you like by following the structure shown below.
function [y] = some_function(x, y)
y = 3*x.*y
end
Now, you can use the some_function
function in the exact same way in your script.
Logical and relational operators
Here are the ways to write logical operators in Matlab.
Type | Command | Example | Result |
---|---|---|---|
And | & |
true & false |
false |
Or | | |
true | false |
true |
Exclusive or | xor |
xor(true, false) |
true |
Not | ~ |
~false |
true |
Relational operators are also written the following way.
Type | Command | Example | Result |
---|---|---|---|
Less than | < |
3 < 4 |
true |
More than | > |
3 > 4 |
false |
Less or equal than | <= |
3 <= 4 |
true |
More or equal than | >= |
3 >= 4 |
false |
Equal to | == |
3 == 4 |
false |
Not equal to | ~= |
3 ~= 4 |
true |
Be careful not to mistake the equality operator ==
(compares values together) with variable assignments =
(assigns value(s) to a variable).
Loops and statements
for
loops iterate a set of statements for a given vector of values.
for i = 1:10
disp(i)
end
while
loops execute a statement until a specific condition is satisfied.
i = 0;
while i < 10
i = i+1;
end
disp(i)
An if
statement executes a block of code only if the associated condition is met.
x = 1e3
if sin(x) > 0.5
disp(sin(x))
elseif sin(x) < 0
disp(1)
else
disp('Hi!')
end
Plots
Single
The plotting syntax takes as input x
and y
coordinates and does the job for you!
x = linspace(0, 2*pi, 100)
y = sin(x)
plot(x, y)
Multiple
If you want to plot multiple graphs on top of each other, you can use the hold
keyword as shown here.
x = linspace(0, 2*pi, 100);
y_1 = sin(x);
y_2 = cos(x);
plot(x, y_1)
hold on
plot(x, y_2)
hold off
If you want to plot each new line with a different color, use hold all
instead of hold on
.
Saving
In order to save your plot to a file, use the syntax below.
saveas(gcf,'my-plot.png')
Good practices and extra tips
- If you need help on something, use the command
help
, followed by what you are looking for, e.g.help diag
. - Each time you start a session, use the command
clc
to clean the command history,clear all
to delete previously assigned variables andclose all
to close all figures. This will let you have a fresh start! - If for some reason you would like to delete previous command history, just type
com.mathworks.mlservices.MLCommandHistoryServices.removeAll
in the command window. - Add
;
at the end of a statement for which you do not want to see the output. - Separate different sections of your script with the line
%%
so that you can later run each of them separately. - Press
Ctrl + C
if you wish to interrupt current computations.