Skip to main content

Section 3.6 Octave/MATLAB recap

Conditionals. The instruction if ... else ... end allows programmers to tell MATLAB to do different things depending on some logical condition. Common logical conditions consist in comparisons of two mathematical expressions through the operators
  • < (smaller than);
  • <= (smaller than or equal to);
  • > (greater than);
  • >= (greater than or equal to);
  • == (equal to);
Recall that = is an assignment, the logical operator testing the equality of two expressions is ==.

Comparing floating-point numbers. Due to the ever-present round-off errors, it is never a good idea comparing with == two floating point numbers, as the following code shows:
A better solution is to fix some tolerance eps and asking that the distance between the two numbers is smaller than that:
Of course in this case by "equal" we really mean "close enough to each other for our purposes".

Defining functions. What if we need to define, within MATLAB, a function, say \(f(x)=\sin x-3x^4\text{?}\) the simplest solution is using the syntax as in the example below:
In MATLAB jargon, these are called Anonymous functions.