How to Create Function in MATLAB: Syntax and Example
In MATLAB, you create a function by starting with the
function keyword followed by the output variables, the function name, and input variables in parentheses. The function code goes below this line, and the file must be saved with the same name as the function.Syntax
The basic syntax to create a function in MATLAB is:
- function: keyword to define a function
- [outputs]: output variables in square brackets (use no brackets if only one output)
- = functionName(inputs): function name and input variables in parentheses
- The function code follows below this line
The function file must be saved with the same name as functionName and with a .m extension.
matlab
function [output1, output2] = functionName(input1, input2)
% Function code here
endExample
This example shows a function named addAndMultiply that takes two inputs and returns their sum and product.
matlab
function [sumResult, productResult] = addAndMultiply(a, b)
sumResult = a + b;
productResult = a * b;
endOutput
[sumResult, productResult] = addAndMultiply(3, 4)
sumResult =
7
productResult =
12
Common Pitfalls
Common mistakes when creating functions in MATLAB include:
- Not saving the function file with the same name as the function.
- Forgetting the
endkeyword (optional in simple functions but recommended). - Mismatching the number of output variables when calling the function.
- Using variables inside the function without defining them as inputs or outputs.
matlab
%% Wrong: File name and function name mismatch function y = wrongName(x) y = x^2; end %% Right: File name and function name match function y = squareNumber(x) y = x^2; end
Quick Reference
Remember these tips when creating MATLAB functions:
- Function file name = function name +
.m - Use
functionkeyword to start - List outputs in square brackets if more than one
- List inputs in parentheses
- End function with
end(recommended)
Key Takeaways
Start a MATLAB function with the
function keyword followed by outputs, name, and inputs.Save the function in a file named exactly as the function with a
.m extension.Use square brackets for multiple outputs and parentheses for inputs.
Always check that the function name and file name match to avoid errors.
Include the
end keyword to clearly mark the function's end.