using function in matlab

To create a function in MATLAB, you need to use the function keyword followed by the output variable(s) and input variable(s). Here is the basic syntax of a MATLAB function:

main.m
function [outputVariables] = functionName(inputVariables)
    % function code goes here
end
92 chars
4 lines
  • function keyword signals the start of the function block.
  • [outputVariables] is a list of variable names that the function returns to the calling routine.
  • functionName is the name of the function.
  • (inputVariables) is a list of arguments that the function accepts.
  • function code is the code that executes when the function is called.
  • end keyword marks the end of the function definition.

Here's an example function definition that takes two numbers as input and returns their sum:

main.m
function [result] = sumNumbers(a, b)
    % compute the sum of two numbers
    result = a + b;
end
98 chars
5 lines

You can call the above function from the command window or from another script like this:

main.m
% call the sumNumbers function with input arguments 5 and 10
c = sumNumbers(5, 10);
% print the result to the console
disp(c);
127 chars
5 lines

This will output 15 to the console.

gistlibby LogSnag