% Copy and paste in 'mysum.m' function R = mysum(x,y) R = x + y; end
% Copy and paste in 'mycomparer.m' function[minVal,maxVal] = mycomparer(x,y,z) minVal = min([x,y,z]); maxVal = max([x,y,z]); end
To call a function, provide a correct number of inputs and outputs according to its definition. The inputs can be in the form of values or variables, but the outputs must be variables.
% Call the built-in 'sqrt' function squareRoot = sqrt(4);
squareRoot = 2
mysum introduced before receives two scalar numeric inputs and returns the sum of both values. The function
mycomparer receives three scalar numeric inputs, and returns two outputs containing the minimum and the maximum value in the input.
% Call 'mysum', passing two values sum1 = mysum(2,3);
sum1 = 5
% Call 'mysum', passing a value and a variable a = 5; sum2 = mysum(a,2);
sum2 = 7
% Call 'mycomparer', passing three variables i = 7; j = 5; k = 9; [minValue1,maxValue1] = mycomparer(i,j,k);
minValue1 = 5
maxValue1 = 9
% Call 'mycomparer', passing an incorrect number of inputs [minValue2,maxValue2] = mycomparer(9,10);
Error using mycomparer (line 2) Not enough input arguments.
Note that the advantage of functions is that the caller just need to know what a function does, but not how. This principle is known as “encapsulation”.
I recommend the following books to learn more on functions in MATLAB.
This book was the winner of a Textbook Excellence Award. The sixth chapter covers user-defined functions, scope of variables, debugging, and other aspects related to the development of MATLAB programs.
MATLAB for Engineers (5th Edition)
This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. Chapter 6 explains how to create and call functions.
I also recommend the other tutorials in this series.
- How to Define Functions in MATLAB
- How to Call a Function in MATLAB
- How to Add Help Documentation to a Function in MATLAB
- Local Functions in MATLAB
- Nested Functions in MATLAB
- Visibility of Nested Functions in MATLAB
- Private Functions in MATLAB
- Anonymous Functions in MATLAB
- Inside the Handle of Anonymous Functions in MATLAB
- Functions with Variable Input Arguments in MATLAB
- Functions with Variable Output Arguments in MATLAB
- How to Validate the Number of Input Arguments Passed to a Function in MATLAB
- How to Validate the Number of Output Arguments Passed to a Function in MATLAB
I hope you have learned how to call functions in MATLAB. The source code developed in this tutorial is available at this page.