Functions

If

The If function is used to conditionally execute statements depen

if (expression)
statement;
end

Here we are using the following code:

x = 1;
y = 2;
if (y > x)
fprintf('y is greater than x');
end

This gives a result in the command window of:

y is greater than x

However, this does not account for the other possibilities. Indeed, if x was greater than y, the command window would not return anything. What if they were equal? Luckily, the if function accounts for that using the 'elseif' and 'else' statements. As such, our code can be modified to look like:

x = 1;
y = 2;
if (y > x)
disp('y is greater than x');
elseif (x > y)
disp('x is greater than y');
else (y > x)
disp('x and y are equal');
end

Now, if the values of x or y are changed, the code will adapt to give an appropriate response to the new situation.

Switch

The 'elseif' and 'else' statements are useful but can get a little bit messy when there are a lot of different cases. As such, it might be preferable to use the 'switch' function.
It follows the format:

switch (variable)
case situation_1;
statement_1;
case situation_2;
statement_2;
otherwise;
statement_otherwise;
end

Here we are using it in the following code to identify the degree of an expression:

syms x y;
y = x^2 + 3*x - 5;
z = feval(symengine, 'degree', y);
n = int8(z);
switch n
case 0;
disp('The expression is a constant.');
case 1;
disp('The expression is linear.');
case 2;
case 3;
disp('The expression is cubic.');
otherwise;
disp('The expression has a higher degree.');
end

This gives a result in the command window of:

Creating Functions

Sometimes, it might be useful to create a function as to avoid typing the same text over and over again. This makes the code more compact and easier to read. It is possible to define your own functions.

function output = name_of_the_function(input)
output = expression in terms of input;
end

Here we are creating a function which adds 2 to the input and then divides that sum by said input:

function y = my_function(x)
y = (x + 2) / x;
end

It is important to note that files containing functions cannot contain any other code and their name needs to be the name of the function (here my_function). The created function can then be called from the command window of from other files. As such, typing   my_function(10)   into a new document returns:

ans =
1.2