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 with disp.
  • Use clear to delete variables, and clc to clear the console.

Arrays


  • Some functions to initialize matrices include zeros, ones, and rand. 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 in zeros(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 as start:end or start: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, and std 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, and std, 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") and ylabel("My vertical label").
  • Use hold on and hold 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 of m x n plots, and use nexttile to change the position of the next plot.
  • Choose the location and size of the tile by passing arguments to nextile as nexttile(position,[m,n]).
  • Use heatmap or imagesc 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 with close(), or close all.
  • Save figures with saveas(fig,"results/my_plot_name.png"), where fig is the figure you want to save, and can be replaced with gcf 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 with end. It can also include an else.
  • 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 keyword end.
  • 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.