Academic Block

Logo of Academicblock.net

Functions in MATLAB

Functions in MATLAB are an essential part of programming that allows 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 with the same name as the function. The syntax for defining a function is as follows:

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

1. Example of a simple function to calculate the sum of two numbers:

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

Save this in a file named addNumbers.m. You can call this function as:

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

    12
    

2. Example of a simple function to calculate the square of a number:

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

Call the function in MATLAB:

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

    25
    

Multiple Outputs from a Function

Functions can return multiple outputs. Here’s an example:

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

Call this function as:

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

    Sum: 16
    Difference: 4
    

Nested Functions

You can define one function within another. This allows the inner function to access variables from the parent 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
Output:

    8
    

Anonymous Functions

MATLAB also allows creating one-line functions without a separate file, called anonymous functions:

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

    25
    

Recursive Functions

A function that calls itself is called a recursive function. Below is an example to calculate factorial:

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

Call this function as:

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

    120
    

Functions Returning Functions

A function can return another function as its output:

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

Call this function as:

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

    10
    

Built-in Functions

MATLAB provides a wide variety of built-in functions for common tasks. Some examples include:

Using disp Function

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

    Hello, MATLAB!
    

Using fprintf Function

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

    The sum of 5 and 10 is 15.
    

Using input Function

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

    Enter your name: John
    Hello, John!
    

Useful MATLAB Functions

Here is a table of useful MATLAB functions for various tasks:

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 to compute 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 product.