0
0
MATLABdata~5 mins

Function definition syntax in MATLAB

Choose your learning style9 modes available
Introduction
Functions help you organize your code into small, reusable pieces that do one job well.
When you want to repeat a task many times without rewriting code.
When you want to make your code easier to read and understand.
When you want to break a big problem into smaller, manageable parts.
When you want to test parts of your code separately.
When you want to share code with others or use it in different programs.
Syntax
MATLAB
function [output1, output2, ...] = functionName(input1, input2, ...)
    % Your code here
end
The keyword function starts the function definition.
You list outputs in square brackets and inputs in parentheses.
Examples
A simple function that takes one input and returns its square.
MATLAB
function y = squareNumber(x)
    y = x^2;
end
A function with two outputs: sum and difference of two inputs.
MATLAB
function [sum, diff] = addSubtract(a, b)
    sum = a + b;
    diff = a - b;
end
A function with no inputs and no outputs that just prints a message.
MATLAB
function greet()
    disp('Hello!')
end
Sample Program
This defines a function that multiplies a number by 3. Save as multiplyByThree.m. Then in the command window: answer = multiplyByThree(5); disp(['5 multiplied by 3 is ', num2str(answer)]);
MATLAB
function result = multiplyByThree(num)
    result = num * 3;
end
OutputSuccess
Important Notes
Function files must be saved with the same name as the function (e.g., multiplyByThree.m).
Use comments inside functions to explain what the code does.
Functions can have multiple inputs and outputs, but keep them simple for clarity.
Summary
Functions start with the keyword function followed by outputs, name, and inputs.
They help make code reusable and easier to understand.
Always save function code in a file named after the function.