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
clearto delete variables, andclcto 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:endorstart:increment:end. - Use the keyword
endto obtain the index of the final element. - The colon operator by itself
:selects all the elements.
Loading data
- Use
readmatrixto read tabular CSV data into a program. - Use
mean,min,max, andstdon 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 onandhold offto plot multiple lines at the same time. - Use
legendand add,DisplayName="legend name here"inside the plot function to add a legend. - Use
tiledlayout(m,n)to create a grid ofmxnplots, and usenexttileto change the position of the next plot. - Choose the location and size of the tile by passing arguments to
nextileasnexttile(position,[m,n]). - Use
heatmaporimagescto plot a whole matrix with values coded as color hues.
Writing MATLAB Scripts
- Save MATLAB code in files with a
.msuffix. - 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_nameto get the information in the H1 line. - Create new figures with
figure, or new ‘invisible’ figures withfigure(visible='off'). Remember to close them withclose(), orclose all. - Save figures with
saveas(fig,"results/my_plot_name.png"), wherefigis the figure you want to save, and can be replaced withgcfif 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
ifand finishes withend. It can also include anelse. - Use
elseifto 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
.mextension. The name of the file must be the same as the name of the function defined in the file. - Define functions using the
functionkeyword 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
forto create a loop that repeats one or more operations.