To create a function in Matlab which calculates the difference in the way described, we can use an if statement to compare the two input values and calculate the difference accordingly. The code for this function is as follows:
main.m138 chars8 lines
Here, the function lesser_greater_diff
takes two input arguments a
and b
and returns the difference between them, calculated as the lesser number minus the greater number. The function first uses an if statement to check whether a
is greater than b
. If this is true, it sets the value of difference
to a - b
, otherwise it sets the value to b - a
.
By doing so, the value of difference
will always be positive or zero, and it will always be the difference between the lesser number and the greater number.
We can call this function with different input values, as shown in the following examples:
main.m175 chars9 lines
In all cases, the output value is the absolute difference between the two input values, calculated as the lesser number minus the greater number.
gistlibby LogSnag