Things ENGG1801 Did Not Teach You

Introduction

The issue with many introductory programming courses lies in their lack of flexibility. ENGG1801, at least when I completed it, was the worst offender of this. If it was not something covered in lectures, it was apparently something you should not know and you were penalised for it. Not only is this bad practice in disallowing people to optimise their own coding style, but it makes code exponentially more verbose and harder to troubleshoot.

The basics of coding never change, and I admit that is what 1801 covered, but reliability, robustness and readability are integral to at least engineering/scientific code which is built for one particular purpose and nothing outside of that. It is those three components that no subject teaching coding can cover with any justice unless it is open ended and you are given the freedom to choose how to tackle a problem.

The things you really oughta know

1. Clear Axis: cla

Often when you are plotting things, you run your code about 50 times to get something right. The practice taught is to close the figure each time and reinitialise it to prevent plotting multiple times on the same figure. Computationally, this takes an extra few seconds which doesn’t seem like much unless you have half an hour before you’ve got to submit something. Every second in this case counts.

clf closes the entire figure, which is handy once your done, cla on the other hand does not. MATLAB does not close the window in this case, it clears the axis. The ticks, title, labels etc. all remain, but the content of the plot does not. This is especially handy to call midway through a large portion of code when a parameter of your plot needs to change, but the information it displays does not.

This opens the doors to iterative plotting where certain functions can be called via a loop, plotting new information each time with speed. If there is no need to close something, don’t.

2. A New Way to for Loop

This is probably one of the handiest things I stumbled across.

Most of the loops you’re taught to do are initialised using:

for i = n:m
.
.
.
end

Where the loop runs through consecutively m-n times, updating i accordingly. But this is limited to going up or going down consecutive times. What if you were able to go through any vector consecutively?

Well that is exactly what a for loop is intended to do, but obviously something skipped over in 1801. For elements of this, do this.

So that means that you can really customise what you want that loop to do. If you wanted to loop through colours, function names, or any inputs required to test. This means you can test things quite rigorously by giving a range of inputs to the function.

Some examples:

% Certain numerical inputs
n = [13 68 45 3:5:982 12+16i]

% Strings (useful for colours or logic based functions)
n = ['c' 'ro' 'b.x']

for i = n
.
.
.
end


% Functions
n = {@fn1 @fn2 @fn3}

for i = n

  result = i{1}(inputs)

end

% OR probably a nicer way of doing it, accessing any function needed in the vector
for i = 1:length(n)

  fn = n{i}

  result = fn(inputs)

end

3. Local functions and function handles

You’ll notice in the above that functions were accessed by using an @ symbol in front of the function name. Often it is quite handy to rename functions from long descriptive titles to shorter ones. This is done using function handles.

Take for example the function:

function out = quadratic(a,b,c,x)

out = a*x^2+b*x+c;

end

Should another function or variable have a similar name, it may not be best to use this name and so another should be assigned. Changing the name however means every bit of code that uses the function will also need to change to continue working, which is not preferable. This can be avoided using function handles.

q1 = @quadratic;

disp(q1(a1,b1,c1,x1))

This same functionality gives rise to local functions which have no necessity to be called from a separate file.

fn = @(x,y,z) x^2+y^2+z^2;

disp(fn(x1,y1,z1))

This is most useful for equations that need to be called several times but are specific to the task contained within the code. Self containing this code prevents the need to write extra files that perform a single and simple numerical purpose.

4. Autosaving figures

There is no real need to click on a figure and save it manually, and when you are generating more than 2 or 3 figures it can be quite annoying if the code used to generate the figures takes more than a second or so. Pictures can be generated within the code after the figure has finished plotting, with a single file name, at a specified size and in particular file types. MATLAB figures when saved manually only generate to the size of the window, so are often far smaller than needed and can blur when placed into documents.

You can save figures automatically using:

print(filename,filetype)

The filetype I use to include things in \(\LaTeX\) documents is -depsc which is that of a colour .eps file.

To alter the size of the image, this should be placed before the print command.

fig = gcf;
fig.PaperUnits = 'centimeters';
fig.PaperPosition = [0 0 xLength yHeight];

Particularly useful when running an Overleaf document inside of a GitHub repository - figures can auto-update in your document.

5. Autoimporting data

I agree it is important to know how to csvread (or actually the more general version dlmread), but not all csv files or data files are easy to deal with, and often have headers, mixtures of text and numbers and can cause issues when importing.

In the “Home” tab, click on import data and select the file. You can then access the data in a MATLAB table or cell array format which preserves text and numerical inputs which are almost always in the same file together. If you click autogenerate code, you can paste this import code into the beginning of your own code, which is far easier than writing your own table import script.

6. Custom axis ticks and font defaults

When writing reports consistency in font is fairly important, and this is something that most people do not bother to do on figures. Whilst the following code is for \(\LaTeX\) font and styles, it is also possible to change to any font installed on your computer.

set(groot, 'defaultAxesTickLabelInterpreter','latex')
set(groot, 'defaultAxesFontSize', 11)
set(groot, 'defaultLegendInterpreter','latex')
set(groot,'defaultTextInterpreter','latex')
set(groot,'DefaultAxesXGrid','on')
set(groot,'DefaultAxesYGrid','on')

7. Add-ins are incredibly useful

Self explanatory but this makes MATLAB extremely versatile. Add-ins make your life easy. Here’s a few I’ve found useful:

  • gramm: emulates ggplot (or grammar of graphics plot) which makes data stand out. Has many more plot options than native MATLAB and really is a must for anything involving data and statistics presentation.
  • cbrewer: gives access to more colourmaps that are used in cartography as defined by ColorBrewer (C. Brewer, M. Harrower, Pennsylvania State University). Good for much more striking and customisable colourmaps when displaying data.
More to come?