Open In App

Function with Multiple Inputs in a Script File in MATLAB

Last Updated : 11 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. In this article, we will see a function with multiple inputs in a script file in MATLAB. 

Steps:

The steps below can be used to build a function with multiple inputs in a MATLAB script file:

  • Launch a fresh function in MATLAB.
  • To create the function, use the code provided here:
     

function [output1, output2, …] = functionName(input1, input2, …)

Where functionName is the name of your function, input1, input2,…, is the list of its input parameters, and output1, output2,…, is the list of its output arguments.

  • Write the function’s body, which can contain any MATLAB code you like. Use the input arguments in your computations, you must.
  • At the conclusion of your code, use the following syntax to assign values to the output arguments:  
output1 = ...
output2 = ...
  •  The script file should be saved with the same name as your function and the a.m suffix. 
     

Here is an example of a function in a MATLAB script file with numerous inputs:

Example 1:

Matlab




function [sum, difference] = myFunction(x, y)
%  determines the difference 
% between and total of two numbers.
  
difference = x - y;
sum = x + y
end


The function in this example gives two output arguments, sum, and difference, and accepts two input arguments, x, and y. The function’s body calculates the input arguments’ sum and difference before assigning the findings to the output arguments.
 

Example 2:

Matlab




function output = multiply_and_add(x, y, z)
  
% This function uses three inputs 
% (x, y, and z), multiplies the first two,
% and then adds the third input. 
% The output is the outcome.
  
output = x * y + z;
end


This example shows how the function multiply_and_add multiplies the first two input parameters (x and y) before adding the third input argument. (z). The outcome of this process is saved in the output variable, which the method then returns.

Here is an illustration of how you could use the command window to execute this function:

Output:

 

In this case, the parameters 6, 5, and 2 are used to invoke the multiply-and-add function. The code multiplies 6 and 5 to get 30, adds 2 to get 32, and then returns 30. The variable a is then used to record this outcome.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads