Academic Block

Functions in MATLAB Get Certified

Functions in MATLAB are an essential part of programming that allow you to encapsulate code into reusable blocks. They make your code modular, easier to read, debug, and maintain.

Defining Functions

Functions in MATLAB are defined in separate files that have the same name as the function. The basic syntax is:

% Syntax for a function
function output = functionName(input)
    % Your code here
end

1. Example of a simple function that calculates the sum of two numbers (save as addNumbers.m):

% Custom Function Example: Add Two Numbers
function result = addNumbers(a, b)
    result = a + b;
end

You can call the function as follows:

result = addNumbers(5, 7);
disp(result);

Expected output:

12

2. Example of a function that calculates the square of a number (save as squareNumber.m):

% Save this in a file named squareNumber.m
function square = squareNumber(x)
    square = x^2;
end

Call the function:

result = squareNumber(5);
disp(result);

Expected output:

25

Multiple Outputs from a Function

A function can return more than one value:

% Function with Multiple Outputs: Sum and Difference
function [sumResult, diffResult] = computeSumAndDifference(a, b)
    sumResult = a + b;
    diffResult = a - b;
end

Call the function:

[sumVal, diffVal] = computeSumAndDifference(10, 6);
disp(['Sum: ', num2str(sumVal)]);
disp(['Difference: ', num2str(diffVal)]);

Expected output:

Sum: 16
Difference: 4

Nested Functions

A function can be defined inside another function. The inner function can access variables that belong to the outer function’s workspace.

% Nested Functions Example
function mainFunction()
    x = 5;
    y = 3;
    result = nestedAddition(x, y);
    disp(result);
    function sum = nestedAddition(a, b)
        sum = a + b;
    end
end

Expected output:

8

Anonymous Functions

MATLAB also supports one-line functions that do not require a separate file; they are called anonymous functions.

% Anonymous function syntax
f = @(x) x^2;
result = f(5);
disp(result);

Expected output:

25

Recursive Functions

A function that calls itself is called a recursive function. The classic example is the factorial:

% Recursive Function Example: Factorial
function result = factorialRecursive(n)
    if n == 0
        result = 1;
    else
        result = n * factorialRecursive(n - 1);
    end
end

Call the function:

result = factorialRecursive(5);
disp(result);

Expected output:

120

Functions Returning Functions

A function can return another function handle as its output:

% Function Returning Another Function
function funcHandle = createMultiplier(factor)
    funcHandle = @(x) factor * x;
end

Call the factory and then the returned function:

doubleFunc = createMultiplier(2);
result = doubleFunc(5);
disp(result);

Expected output:

10

Built-in Functions

MATLAB supplies a large library of built-in functions. A few everyday examples are shown below.

Using disp

% Using disp to display a message
disp('Hello, MATLAB!');

Expected output:

Hello, MATLAB!

Using fprintf

% Using fprintf for formatted output
a = 5;
b = 10;
fprintf('The sum of %d and %d is %d.\n', a, b, a + b);

Expected output:

The sum of 5 and 10 is 15.

Using input

% Prompting the user for input
name = input('Enter your name: ', 's');
disp(['Hello, ' name '!']);

Example interaction:

Enter your name: John
Hello, John!

Useful MATLAB Functions

Function
Description
disp
Displays a message or variable value.
fprintf
Prints formatted data to the screen or a file.
input
Prompts the user for input.
size
Returns the size of a matrix or array.
length
Returns the length of the largest dimension.
mean
Calculates the mean of an array.
sum
Calculates the sum of array elements.

Practice Questions

Test Yourself

1. Write a function to compute the factorial of a number.

2. Create an anonymous function that computes the square root of a number and test it.

3. Use fprintf to display a formatted message that includes a user-provided name and age.

4. Write a function that takes two arguments and returns both their sum and their product.