0
0
MATLABdata~5 mins

Input and output arguments in MATLAB

Choose your learning style9 modes available
Introduction

Input and output arguments let you send information into a function and get results back. This helps you reuse code easily.

When you want a function to work with different numbers or data each time.
When you want a function to give back results after doing some work.
When you want to organize your code into small, clear pieces that talk to each other.
When you want to avoid repeating the same code in many places.
When you want to test parts of your program separately.
Syntax
MATLAB
function [output1, output2, ...] = functionName(input1, input2, ...)
    % Your code here
end

Input arguments go inside the parentheses after the function name.

Output arguments go inside square brackets before the equals sign.

Examples
A function with one input and one output. It returns the square of the input.
MATLAB
function result = squareNumber(x)
    result = x^2;
end
A function with two inputs and two outputs. It returns both the sum and difference.
MATLAB
function [sumResult, diff] = addAndSubtract(a, b)
    sumResult = a + b;
    diff = a - b;
end
A function with no inputs and no outputs. It just prints a message.
MATLAB
function greet()
    disp('Hello!')
end
Sample Program

This program defines a function that calculates the area and perimeter of a rectangle given its length and width. Then it calls the function with length 5 and width 3 and prints the results.

MATLAB
function [area, perimeter] = rectangleProperties(length, width)
    area = length * width;
    perimeter = 2 * (length + width);
end

% Call the function
[l, w] = deal(5, 3);
[a, p] = rectangleProperties(l, w);
fprintf('Area: %d\nPerimeter: %d\n', a, p);
OutputSuccess
Important Notes

You can have zero, one, or many input and output arguments.

Output arguments must be assigned values inside the function to return them.

If you do not specify output arguments, the function will not return any value.

Summary

Input arguments let you send data into a function.

Output arguments let you get results back from a function.

Functions help keep your code organized and reusable.