return

Return control to invoking function

Syntax

Description

example

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

If you use return at the command prompt, when MATLAB encounters it, it ceases executing the code and 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 function or command prompt.

Examples

expand all

Return Control to Keyboard

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 isn't 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 function.

Return Control to Invoking Function

In a file, myFunction.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 myFunction(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

At the command prompt, call the function.

myFunction(49)
Square root found at index 2

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

See Also

| | | | | | | | |

Was this topic helpful?