Working With Variables
- Variables store data for future use. Their names must start with a letter, and can have underscores and numbers.
- We can add, substract, multiply, divide and potentiate numbers.
- We can also compare variables with
<
,>
,==
,>=
,<=
,~=
, and use~
to negate the result. - Combine logical operations with
&&
(and) and||
(or). - MATLAB stores data in arrays. The data in an array has to be of the same type.
- You can supress output with
;
, and print a variable withdisp
. - Use
clear
to delete variables, andclc
to clear the console.
Arrays
- Some functions to initialize matrices include
zeros
,ones
, andrand
. They all produce a square matrix if only one argument is given, but you can specify the dimensions you want separated by a comma, as inzeros(rows,columns)
. - To select data points we use round brackets and provide the row and
column indices of the elements we want. They can be just numbers or
arrays of numbers, e.g.
M(5,[3,4,5])
. - Use the colon operator
:
to generate ordered arrays asstart:end
orstart:increment:end
. - Use the keyword
end
to obtain the index of the final element. - The colon operator by itself
:
selects all the elements.
Loading data
- Use
readmatrix
to read tabular CSV data into a program. - Use
mean
,min
,max
, andstd
on vectors to get the mean, minimum, maximum and standard deviation. - Use
mean(array,DIM)
to specify the dimension of your array in which to compute the mean. - For
min
,max
, andstd
, the arguments need to be(array,[],DIM)
instead.
Plotting data
- Use
plot(vector)
to visualize data in the y axis with an index number in the x axis. - Use
plot(X,Y)
to specify values in both axes. - Document your plots with
title("My title")
,xlabel("My horizontal label")
andylabel("My vertical label")
. - Use
hold on
andhold off
to plot multiple lines at the same time. - Use
legend
and add,DisplayName="legend name here"
inside the plot function to add a legend. - Use
tiledlayout(m,n)
to create a grid ofm
xn
plots, and usenexttile
to change the position of the next plot. - Choose the location and size of the tile by passing arguments to
nextile
asnexttile(position,[m,n])
. - Use
heatmap
orimagesc
to plot a whole matrix with values coded as color hues.
Writing MATLAB Scripts
- Save MATLAB code in files with a
.m
suffix. - The set of commands in a script get executed by calling the script by its name, and all variables are saved to the workspace. Be careful, this potentially replaces variables.
- Comment your code to make it easier to understand using
%
at the start of a line. - The first line of any script or function (known as the H1 line) should be a comment. It typically includes the name of the program, and a brief description.
- You can use
help script_name
to get the information in the H1 line. - Create new figures with
figure
, or new ‘invisible’ figures with figure(visible=‘off’). Remember to close them withclose()
, orclose all
. - Save figures with
saveas(fig,"results/my_plot_name.png")
, wherefig
is the figure you want to save, and can be replaced withgcf
if you want to save the current figure.
Making Choices
- Use conditional statements to make choices based on values in your program.
- A conditional statement block starts with an
if
and finishes withend
. It can also include anelse
. - Use
elseif
to nest conditional statements. - Use
&&
(and),||
(or) to combine logical operations. - Only one of the statement bodies is ever executed.
Creating Functions
- A MATLAB function must be saved in a text file with a
.m
extension. The name of the file must be the same as the name of the function defined in the file. - Define functions using the
function
keyword to start the definition, and close the definition with the keywordend
. - Functions have an independent workspace. Access variables from your workspace inside a function by passing them as inputs. Access variables from the function returning them as outputs.
- The header of a function with inputs an outputs has the form:
function [output_1,output_2,...] = function_name(input_1,input_2,...)
- Break programs up into short, single-purpose functions with meaningful names.
Repeating With Loops
- Use
for
to create a loop that repeats one or more operations.