MATLAB Flow Control and Plotting

Video

Motivation

MATLAB is a programming language in its own right, and it is reasonable to treat it as one. Today we are going to look at the basics of MatLab scripting - looping through generated plots.

Flow Control

For a (mostly) complete list of your flow control options, you can view the official documentation.

For now, we will just cover the two basics - conditionals and loops.

Conditionals

Conditionals should be easy in any language, and MATLAB is no exception.

Like with NumPy, comparisons on matrices provide Truth Arrays - useful for parallelizing - that we can investigate with any and all.

x = linspace(0,10,11)
if all(x>10)
    fprintf("All Big")
elseif any(x>10)
    fprintf("At Least One Big")
else
    fprintf("None Big")
end

Flow control blocks are ended with the end command.

MATLAB is not whitespace sensitive in the way Python is, so indentation is purely for convenience.

Loops

MATLAB supports for and while loops. (note that it is good practice to never while 1 loop; rather, use your math knowledge to set a reasonable upper bound on execution and for loop instead.)

for i=1:10
    if i<3
        continue
    elseif i>5
        break
    end
    fprintf("i=%d\n",i)
end
while i>2
    i = i-1
end

MATLAB supports the break and continue operators, which work similarly to Python.

Why Not To

We have already briefly discussed how computers are particularly efficient at parallel runs of the same computations on different data (especially linear algebra on GPUs). MATLAB, built on the same technology, is no different.

We have not yet touched upon the fact that modern computers also do a bit of getting-ahead-of-themselves. any break in that flow - such as a conditional in a loop or if statement - can actually throw off the computer's groove a bit. You may have heard about Spectre - a really interesting vulnerability that exploited this "predictive" execution.

In general, this means that you should only use conditionals if you have to, if it is more convenient for you than it is costly for the machine, or you have profiled to find they are faster in this instance.

In addition, MATLAB is relatively quite slow at running conditionals, loops, the creation and destruction of objects, and in general most non-linear-algebra tasks. They expect you to - and you should - do as much of what you want to do as linear algebra.

Plotting

MATLAB was the main inspiration for MatPlotLib's interface, and so its plotting is very similar.

x = linspace(0,2*pi,100)
y = sin(x.^2)
plot(x,y)
title("A Plot Title")
xlabel("An X-Label")
ylabel("A Y-Label")
legend("sin(x^2)")

However, MATLAB is - again - not particularly object oriented, and full of hidden states; so it contains one active figure, with a new one created when you render a plot.

To disable the automatic new figure, so that you can plot multiple things to the same axes, further customize a plot, or do subplots, run:

hold on

To deliberately clear the figure,

clf

And when you no longer want to keep plots,

hold off

Subplots

Subplots are created with the subplot(m,n,p) command syntax - where p is the position in lexicographic order:

subplot(2,1,1)
x = linspace(0,10)
plot(x,sin(x))
title("Sin(x)")
subplot(2,1,2)
plot(x,cos(x))
title("Cos(x)")

Note that these titles support limited $\LaTeX$ syntax.

Plot Types

I won't get into the plot types - or their examples - here.

This is because MATLAB does a pretty good job of this in their editor's "Plot" tab; just select the variables you want to plot, assign them to their roles, and click a plot in the tab!

It will print in the console the default example code for generating that plot, and submit it to your current active figure.

Note that it does not respect subplot selection, instead modifying the most recently modified plot (or creating a new one). To do subplots you will likely have to figure out the code for the plot you want and run it yourself. However, this can be a quick and easy way to play around with your data and plotting it.

The plot types change depending on the number, type, and geometry of selected variables, so play around!

Assignment

Graded Assignment: Using the CSV loading tools, load in a dataset of interest to you and plot it using MatLab. You may find the tool from the MatPlotLib lecture useful.

Department of Mathematics, Purdue University
150 N. University Street, West Lafayette, IN 47907-2067
Phone: (765) 494-1901 - FAX: (765) 494-0548
Contact the Webmaster for technical and content concerns about this webpage.
Copyright© 2018, Purdue University, all rights reserved.
West Lafayette, IN 47907 USA, 765-494-4600
An equal access/equal opportunity university
Accessibility issues? Contact the Web Editor (webeditor@math.purdue.edu).