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.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#
The repayments for a loan can be calculated using the formula
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:
Replace variables
a
tof
with suitable descriptive variable namesUse spaces to improve the code formatting
Add comments to briefly explain what the program is doing
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 %%
.
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.