This guide is intended to be a supplement/reminder of some basic programming concepts in MATLAB. At the end of most sections there are links to MathWork's documentation related to the section. I highly recommend reading/using the documentation as it can be very helpful.
- Brief Interface Overview
- Comments
- Variables
- Basic Operations
- Code Cells
- Input/Output
- Conditionals
- Loops
- Arrays/Matrices
- Functions
Here are some of the most important parts of the interface.
- This will run the code in the currently open script file.
- This will run the currently selected code cell.
- This is where you write your Matlab code.
- This shows you variables in your workspace and their values.
- This is where your script output will go. You can also type commands into this window.
A comment is a note in your code, they will not affect your code. Blank lines also do not affect your code. In Matlab there are two types of comments: single line and multiline comments. Single line comments begin with a %
at the start of a line and multiline comments start with %{
and end with %}
. You can see an example of both comments below:
% This is a single line comment.
%{
This is a
multiline
comment.
%}
Variables can hold information inside of them. For example you can have a variable named answer which holds the answer to some math calculation. Something to keep in mind is that all variables are multidimensional arrays. There are many variable types but below you can see a list of commonly used types.
- double
- single
- int32
- int64
- char
- string
- logical
%{
In Matlab all numeric values are by default doubles.
You can use a function of a numeric data type to use other types.
All of the variables in this example are 1x1 matrices.
Literal constants are fixed values in your code.
10, 10.0, and 'Hello World' are some examples of literal constants.
%}
double_example = 10.0;
double_example_two = 10; % this is also a double
single_example = single(10.0); % single() creates to a 32 bit floating point number
int32_example = int32(10); % int32() creates to a 32 bit integer
int64_example = int64(10); % int64() creates to a 64 bit integer
char_example = 'Hello World'; % single quotes to make a character array
string_example = "Hello World"; % double quotes to make a string array
% You can access a single character by using () on a character array
c = char_example(1); % this puts 'H' into c
% () on strings accesses each string phrase, so "Hello World" will be the first phrase
s = string_example(1); % this puts "Hello World" into s
logical_example = true; % logical values can either be true
logical_example = false; % or false
There are a lot of other types in Matlab. I highly recommend looking here to learn more about types and their functionality. Matlab will by default output variables to the console. You can put a semicolon (;
) at the end of a line to prevent the console output.
You can perform some math operations on as one would expect using arithmetic operators (+, -, *, /, ^). Parenthesis also work as expected for math operations. You can perform operations on variables and literal constants. For right now we will just look at operations on 1x1 matrices.
% Some examples of using arithmetic operators and their outputs.
add = 10 + 10; % 20
sub = 10 - 5; % 5
mult = 2 * 2; % 4
div = 10 / 5; % 2
pow = 2 ^ 2; % 4
paren = (2 + 2) * 2; % 8
var = (add - sub) * 4 / div; % 30
If you do not put the result of an operation into a variable, by default matlab will put your result into a variable called "ans" and print it. You can find a helpful page for operators here. This page has links to all of the operators and their precedence.
Code cells are sections of code that can be run separately. Variables from other code cells can be used as long as the other code cell has already been run. You can run a individual selected code cell by either clicking the "Run Section" Button or by pressing Ctrl + Enter (CMD + Enter on Mac). Code cells are useful for having parts of code that can be changed and ran on their own or for running code once that does not change. Some examples for uses of code sections are: changing variables that change results in other code sections, loading a large amount of unchanging data, and high costing computations.
%% This is a code cell
B = 5;
%% This is another code cell, it depends on the first code cell to be ran first.
A = B + 5;
%% This is a third code cell, it can be run on its own.
C = 5 + 10;
You can read input from the console in Matlab by using input(prompt) where prompt is any character array or string array. Keep in mind when inputting from the console by default any number will be a double. You can wrap your input with int32() to make it an integer, with quotes for a string, and with most other functions.
% input syntax:
%{
x = input(prompt)
%}
in = input("Enter a number");
% You can also use a variable as your prompt
prompt = "Enter a second number";
in2 = input(prompt);
You can also display output to the console by using disp(output) where output is what you want to print to display. You can also use fprintf to use C style formatting.
% display syntax:
%{
disp(X)
%}
% This is a continuation of the code from above.
disp(in)
fprintf("Your second number is: %f\n", in2)
In our fprintf above %f
is replaced by in2 (floating point number). For integers you can use %d
. The \n
is a new line character which prints out a new line. You can read more about input and output at the following: input, disp, fprinf.
A conditional statement chooses a different block of code to run based on some condition. There are two types of conditional statements in Matlab if
and switch
. Both statements must end with the end
keyword.
% if statement syntax:
%{
if expression
statements
elseif expression
statements
else
statements
end
%}
% if statement example
% Notice the tabbed spacing to specify the blocks of code for each statement.
num = 5;
if num <= 5 % checks if the variable num is 5 or less
disp("5!"); % this will run if num is 5
elseif num == 10 % checks if num is 10 ONLY if num is greater than 5
disp("10!"); % this will run if the above line is true
else % runs if num is not 10 and greater than 5 (essentially any other case)
disp("Neither!"); % this will run if the above line is true
end % You need to end an if statement with an end
% switch statement syntax:
%{
switch switch_expression
case case_expression
statements
case case_expression
statements
...
otherwise
statements
end
%}
% switch statement example
% Notice the tabbed spacing to specify the blocks of code for each statement.
num = 3;
switch num
case 1 % checks if num is 1
disp(1)
case 2 % checks if num is 2
disp(2)
otherwise % runs if num is not 1 or 2 (all other cases)
disp("Other num")
end % You also need to end a switch statement with an end
You may have noticed that the if statement can support testing for inequalities (or any logical value) while the switch statement can only check exact equality cases, this is the major difference between the two. You can read more about conditionals at the following: conditional statement, if, switch, relational and logical operators.
Loops can run a block of code multiple times. There are two types of loops: for loops and while loops. For loops run a specific number of times and while loops run while a condition is true. You can start each loop using if
or while
and they both must end with the end
keyword. Also break
will exit a loop and continue
will goto the next iteration of the loop.
% for loop syntax:
%{
for index = values
statements
end
%}
% This example prints out the numbers 1-10.
for index = values
st
for i = 1:10
disp(i)
end
% while loop syntax:
%{
while expression
statements
end
%}
% This example asks for numbers until 5 is entered.
while 1
x = input("Enter a number");
if x == 5
break
end
end
Loops can be very helpful, you can avoid writing the same code in many cases by using a loop. Some more reading about loops in Matlab can be found here: loops, for, while, break, continue.
As said before all variables in Matlab are multidimensional arrays. This means you can make your own matrices and apply operations to them. Lets first look at some examples of creating some arrays and matrices.
%{
You can define the elements of an array or matrix by using [].
You can either use spaces or commas to seperate elements.
Use a semicolon to separate the rows of a matrix.
You can get the value at an index by doing matrixname(row, column).
%}
% array_spaces and array_commas are known as row vectors.
array_spaces = [1 2 3 4];
array_commas = [1, 2, 3, 4];
matrix_example = [1 2 3; 4 5 6; 7 8 9;];
array_spaces(1) % this is 1
matrix_example(1,2) % this is 2
Now lets take a look at some matrix operations. Arithmetic operators will follow linear algebra rules. For example you can multiply a 2x3 matrix with a 3x2 matrix, but you cannot multiply a 3x2 matrix with a 3x2 matrix. You can also put a .
in front of some operators (*
, ^
, /
, \
) to do element wise operations.
matrix_one = [1 2 3; 4 5 6; 7 8 9;];
matrix_two = [1 2; 3 4; 5 6;];
matrix_mult = matrix_one * matrix_two % this is valid (3x3 * 3x2)
bad_matrix_mult = matrix_two * matrix_two % this is not valid (3x2 * 3x2)
element_wise_mult = matrix_one .* [1 2 3]
%{
[1 2 3] will implicitly expand from a 1x3 matrix to a 3x3 matrix.
[1 2 3] -> [1 2 3;
1 2 3;
1 2 3]
}%
You can read more about this topic here: arrays/matrices, array/matrix operations, and multidimensional arrays.
You can pass input into a function you define and then get some output from that function. Functions can reduce repetition of code and help keep your code organized. Functions can either be in a function file or at the end of a script file. A function file must have the same name as the first function in the file. A script filename cannot be the same as a function in the script file.
% function syntax
%{
function [y1,...,yN] = myfun(x1,...,xM)
end
%}
% y1,...,yN are your outputs and x1,...,xM are inputs.
a = add_three(1, 2, 3)
[b, c] = square_and_cube(3)
% notice how the function definitions are at the bottom
function s = add_three(x,y,z)
s = x + y + z;
end
function [s, c] = square_and_cube(x)
s = x * x;
c = x * x * x;
end
Some more information about functions can be found here: functions.