sub function in matlab

In MATLAB, you can create a sub-function inside a function to modularize your code and make it more organized. A sub-function can only be accessed by the primary function in which it's defined.

The syntax for creating a sub-function is as follows:

main.m
function [output1,output2,..] = mainFunction(input1,input2,..)
% mainFunction Definition
..
..
..
[outputA,outputB,..] = subFunction(inputX,inputY,..);
..
..
end

function [out1,out2,..] = subFunction(in1,in2,..)
% subFunction Definition
..
..
end
248 chars
16 lines

As you can see, the sub-function is defined inside the main function block, and it has its own inputs and outputs.

Here's an example to demonstrate how to use a sub-function in MATLAB:

main.m
function [result1,result2] = calculateSumAndAvg(numbers)
% calculateSumAndAvg: function to calculate the sum and average of a list of numbers
%
% Syntax:
%   [result1,result2] = calculateSumAndAvg(numbers)
%
% Input:
%   numbers = a row vector of numbers
%
% Output:
%   result1 = the sum of the numbers
%   result2 = the average of the numbers
%
    sum = calculateSum(numbers);
    avg = calculateAvg(numbers);
    result1 = sum;
    result2 = avg;
end

function [sum] = calculateSum(numbers)
    % calculateSum: sub-function to calculate the sum of a list of numbers
    sum = 0;
    for i = 1:length(numbers)
        sum = sum + numbers(i);
    end
end

function [avg] = calculateAvg(numbers)
    % calculateAvg: sub-function to calculate the average of a list of numbers
    sum = calculateSum(numbers);
    avg = sum / length(numbers);
end
846 chars
33 lines

In this example, we have a main function calculateSumAndAvg that takes a row vector of numbers as input and calculates their sum and average by calling the sub-functions calculateSum and calculateAvg. Both sub-functions are defined inside the main function block and have their own inputs and outputs.

gistlibby LogSnag