8.7. Formatting code#

It is good programming practice to format your code using spaces, blank lines and commands so that it can be easily read. Guidelines for formatting MATLAB code can be found in the MATLAB Programming Style Guide (a wiki maintained by contributors independent of MathWorks) and this section covers some of the basics.

8.7.1. Comments#

A comment in a program is text that is ignored by MATLAB when the code is executed and are useful to helping people understand the program. Comments in MATLAB can by entered using the % symbol

% this is a comment

Here any text on the same line to the right of % is ignored. These are useful for short comments.

Comments are useful for telling someone (and yourself) what a program and individual lines of a program does. Add some comments to your program similar what is shown below.

clear % Clear all variables
clc   % Clear command window

% 1. MATLAB Basics

% Print the header
fprintf("\nDegrees to radians conversion\n-----------------------------")

% Define the variables
angle_in_degrees = 45;

% Calculate the angle in radians
angle_in_radians = angle_in_degrees * pi / 180;

% Print the angle in degrees and radians
fprintf("\nangle in degrees = %6.3f\n", angle_in_degrees)
fprintf("angle in radians = %6.3f\n", angle_in_radians)

8.7.2. Spaces#

In a MATLAB program spaces are ignored, however it is common practice to use spaces either side of the arithmetic operators so that it is more readable. It is also advisable to separate blocks of code with a blank line.

For example the code

1*2+3*4+5/6

is equivalent to the code

1 * 2 + 3 * 4 + 5 / 6

8.7.3. Exercise#

Exercise 8.6

The repayments for a loan can be calculated using the formula

\[ P = \frac{rV}{1 - (1 + r)^{-n}}, \]

where

  • \(P\) is the monthly repayment

  • \(V\) is the value of the loan

  • \(r\) is the interest rate per period

  • \(n\) is the number of periods

The program below calculates the monthly repayments for a mortgage of value £200,000 taken out over 20 years with a fixed annual interest rate of 4%.

% Exercise 8.6
a=200000;
b=20;
c=4;
d=12*b;
e=c/100/12;
f=e*a/(1-(1+e)^(-d));
a
b
c
f

Copy and paste this program into your Python file and edit it to do the following:

  1. Replace variables a to f with suitable descriptive variable names

  2. Use spaces to improve the code formatting

  3. Add comments to briefly explain what the program is doing

  4. Edit the print commands so that the program outputs the loan details and the monthly repayment amount in the following format

Loan repayment calculator
-------------------------
Loan amount          : £xxxxxx.xx
Loan duration        : xx years
Annual interest rate : xx%

Monthly repayment    : £xxxx.xx

Hint: to print a % symbol using the fprintf() function use %%.