without using the absolute value function, write your function so that difference will always be the lesser number minus the greater number. in matlab

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.m
function difference = lesser_greater_diff(a, b)
    if a > b
        difference = a - b;
    else
        difference = b - a;
    end
end
138 chars
8 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.m
>> difference = lesser_greater_diff(5, 10)
difference = 5

>> difference = lesser_greater_diff(10, 5)
difference = 5

>> difference = lesser_greater_diff(5, 5)
difference = 0
175 chars
9 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