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 (
Terminalon Mac/Linux andPuTTYor 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/2) | 1 |
| Cosine | cos | cos(pi) | -1 |
| Tangent | tan | tan(0) | 0 |
| Arcsine | asin | asin(1) | 1.5708 |
| Arccosine | acos | acos(-1) | 3.1416 |
| Arctangent | atan | atan(0) | 0 |
Exponentials and square root
The following functions are often used:
| Type | Command | Example | Result |
|---|---|---|---|
| Exponential | exp | exp(1) | 2.7183 |
| Natural logarithm | log | log(exp(1)) | 1 |
| Logarithm base 10 | log10 | log10(100) | 2 |
| Square root | sqrt | sqrt(9) | 3 |
Rounding and remainder
The following functions can be useful:
| Type | Command | Example | Result |
|---|---|---|---|
| Round to nearest integer | round | round(2.6) | 3 |
| Round towards zero | fix | fix(2.6) | 2 |
| Round towards plus infinity | ceil | ceil(2.1) | 3 |
| Round towards minus infinity | floor | floor(2.9) | 2 |
| Remainder after division | rem | rem(7, 3) | 1 |
Vectors
Syntax
To define a vector, use square brackets [ ] and use either spaces or commas to separate the elements.
- Row vector: To define a row vector, type:
v = [1 2 3]
- Column vector: To define a column vector, you can either use the transpose operator
'on a row vector or separate the elements with semicolons;:
v = [1 2 3]'
v = [1; 2; 3]
Quick generation
For vectors with a high number of elements, you can use the following commands:
| Command | Result |
|---|---|
[a:step:b] | Vector starting from a to b with a step of step |
linspace(a, b, n) | Vector of n elements between a and b included |
zeros(1, n) | Vector of n zeros |
ones(1, n) | Vector of n ones |
Common operations
By noting v and w two vectors and k a constant, here are common operations:
| Operation | Command |
|---|---|
| Addition | v + w |
| Subtraction | v - w |
| Element-wise multiplication | v .* w |
| Element-wise division | v ./ w |
| Element-wise exponentiation | v .^ k |
| Dot product | dot(v, w) |
| Vector length | length(v) |
Matrices
Syntax
To define a matrix, use square brackets [ ] and use semicolons ; to separate the rows.
A = [1 2 3; 4 5 6; 7 8 9]
Quick generation
The following commands are often used:
| Command | Result |
|---|---|
zeros(m, n) | Matrix of size $m\times n$ with zeros |
ones(m, n) | Matrix of size $m\times n$ with ones |
eye(n) | Identity matrix of size $n\times n$ |
rand(m, n) | Matrix of size $m\times n$ with random elements between 0 and 1 |
Common operations
By noting A and B two matrices and k a constant, here are common operations:
| Operation | Command |
|---|---|
| Addition | A + B |
| Subtraction | A - B |
| Multiplication | A * B |
| Element-wise multiplication | A .* B |
| Element-wise division | A ./ B |
| Element-wise exponentiation | A .^ k |
| Matrix transpose | A' |
| Matrix inverse | inv(A) |
| Matrix determinant | det(A) |
| Matrix size | size(A) |
Writing your functions
To write your own function, you have to create a new .m file with the name of your function.
Simple case
If your function has one output y and one input x, the file my_function.m should look like this:
function y = my_function(x)
y = x^2;
end
Advanced case
If your function has multiple outputs [y1, y2] and multiple inputs (x1, x2), the file my_function.m should look like this:
function [y1, y2] = my_function(x1, x2)
y1 = x1 + x2;
y2 = x1 * x2;
end
Mathematical operators
Logical operators
The following operators can be used to perform logical operations:
| Operation | Command |
|---|---|
| AND | & |
| OR | | |
| NOT | ~ |
Relational operators
The following operators can be used to compare two values:
| Operation | Command |
|---|---|
| Equal to | == |
| Not equal to | ~= |
| Greater than | > |
| Greater than or equal to | >= |
| Less than | < |
| Less than or equal to | <= |
Matlab operators
Loops
The following operators can be used to perform loops:
- For loop:
for i = 1:10
disp(i)
end
- While loop:
i = 1;
while i <= 10
disp(i)
i = i + 1;
end
Statements
The following operators can be used to perform statements:
- If statement:
if x > 0
disp('Positive')
elseif x < 0
disp('Negative')
else
disp('Zero')
end
Plots
Single plot
To plot a single vector y against x, use:
plot(x, y)
xlabel('x')
ylabel('y')
title('My plot')
Multiple plots
To plot multiple vectors in the same figure, use hold on:
plot(x, y1)
hold on
plot(x, y2)
legend('y1', 'y2')
Saving plots
To save a plot, use saveas:
saveas(gcf, 'my_plot.png')
Good practices
Extra tips
- Use
%to write comments in your code. - Use
;at the end of a line to suppress the output in the command window. - Use
clcto clear the command window. - Use
clear allto clear all variables from the workspace. - Use
close allto close all open figures. - Use
help function_nameto get help about a specific function.
CME 102 | CME 106 - Matlab Tips