The editor gives indications about possible errors (red) and warnings (yellow) on the right had side next to the scroll bar. However there are different types of errors, to explain them we use the following example:
clear
a = input( 'Enter a: ' );
b = input( 'Enter b: ' );
c = input( 'Enter c: ' );
r = b * b – 4 * ac;
x1 = (-b+sqrt(r))/(2*a)
x2 = (-b-sqrt(r))/(2*a)
r = b*b - 4 ac
there is no multiplication sign, *
, between 4
and ac
.r = b*b - 4 * ac
the syntax is ok. Even though the editor will not show a syntax error, the code will fail at run time. This is due to the fact that it believes ac
to be a variable and it is not defined. Therefore we still need to add a *
between the ac
in the example to fix this problem.When a function is written, particular kinds of data for the arguments is often expected. We can use the inbuilt error
function when what the input given makes it impossible to proceed. This call to error can be set to give a message to the program-user before exiting and halting the program immediately. For example, a function which estimates the expected weight for a baby whose age is given in months:
function W = expectedWeight(ageInMonths)
% Usage:
% ... usage text goes here ...
if (ageInMonths < 0)
error('Age cannot be negative')
end
% ... rest of function continues below ...
Another inbuilt function known as warning
can be used when it allows the user to proceed with the input but the results may be unreliable. With call to warning
, the message is reported to the user but it does not exit the program but continues. E.g:
function W = expectedWeight(ageInMonths)
% Usage:
% ... usage text goes here ...
if (ageInMonths > 60)
warning('Really a baby??!')
end
% ... rest of function continues below ...
When writing a program to solve a problem or model a system etc. Adopt the following steps for reliable code with fewer errors:
The aim of this method is to always have a working version of the program. Even if it doesn’t yet do everything it is supposed to do. It helps to avoid trying to write everything in one go, and it tests the program repeatedly and often.