Main Content

return

Return control to invoking script or function

Syntax

Description

example

return forces MATLAB® to return control to the invoking program before it reaches the end of the script or function. The invoking program is a script or function that calls the script or function containing the call to return. If you call the script or function that contains return directly, there is no invoking program and MATLAB returns control to the command prompt.

Note

Be careful when you use return within conditional blocks, such as if or switch, or within loop control statements, such as for or while. When MATLAB reaches a return statement, it does not just exit the loop; it exits the script or function and returns control to the invoking program or command prompt.

Examples

collapse all

In your current working folder, create a function, findSqrRootIndex, to find the index of the first occurrence of the square root of a value within an array. If the square root is not found, the function returns NaN.

function idx = findSqrRootIndex(target,arrayToSearch)

idx = NaN;
if target < 0
   return
end

for idx = 1:length(arrayToSearch)
    if arrayToSearch(idx) == sqrt(target)
        return
    end
end

At the command prompt, call the function.

A = [3 7 28 14 42 9 0];
b = 81;
findSqrRootIndex(b,A)
ans =

     6

When MATLAB encounters the return statement, it returns control to the keyboard because there is no invoking script or function.

In a file, returnControlExample.m, in your current working folder, create the following function to find the index of the first occurrence of the square root of a value within an array. This function calls the findSqrRootIndex function you created in the previous example.

function returnControlExample(target)
    arrayToSearch = [3 7 28 14 42 9 0];
    idx = findSqrRootIndex(target,arrayToSearch);
    
    if isnan(idx)
        disp('Square root not found.')
    else
        disp(['Square root found at index ' num2str(idx)])
    end
end

At the command prompt, call the function.

returnControlExample(49)
Square root found at index 2

When MATLAB encounters the return statement within findSqrRootIndex, it returns control to the invoking function, returnControlExample, and displays the relevant message.

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Version History

Introduced before R2006a

See Also

| | | | | | | | |