Main Content

return

Return control to invoking script or function

Syntax

Description

example

returnforces 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 toreturn. If you call the script or function that containsreturndirectly, there is no invoking program and MATLAB returns control to the command prompt.

Note

Be careful when you usereturnwithin conditional blocks, such asiforswitch, or within loop control statements, such asfororwhile. When MATLAB reaches areturnstatement, 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 returnsNaN.

functionidx = findSqrRootIndex(target,arrayToSearch) idx = NaN;iftarget < 0returnendforidx = 1:length(arrayToSearch)ifarrayToSearch(idx) == sqrt(target)returnendend

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 thefindSqrRootIndexfunction you created in the previous example.

functionreturnControlExample(target) arrayToSearch = [3 7 28 14 42 9 0]; idx = findSqrRootIndex(target,arrayToSearch);ifisnan(idx) disp('Square root not found.')elsedisp(['Square root found at index 'num2str(idx)])endend

At the command prompt, call the function.

returnControlExample(49)
Square root found at index 2

When MATLAB encounters thereturnstatement withinfindSqrRootIndex, 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™.

版本历史

Introduced before R2006a