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:

In the latter case, here is the procedure:

  1. Open a terminal window (Terminal on Mac/Linux and PuTTY or equivalent on Windows)
  2. Access the cluster via the command
ssh your-sunetid@rice.stanford.edu
  1. Enter your SUNet password and choose your favorite 2FA method when prompted
  2. 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:

x = 0:0.01:1

Here, the example will provide a vector of numbers ranging from 0 to 1 by increment of 0.01.

x = linspace(0, 1, 100)

The above example will output a vector of 100 numbers evenly spaced from 0 to 1.

Common operations

[a 3]

will give you [1 2 3] and

[a [3 4]]

will output [1 2 3 4].

x = [1 2 3 4 5]
x(sin(x) > 0.5)
x = 1:10
reshape(x, [2,5])

converts the 10-long row vector x into a matrix with 2 rows and 5 columns.

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

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