evaluateAndCapture
Syntax
Description
evaluates the specified code in the workspace outputDisplay
= evaluateAndCapture(w
,expression
)w
and returns a string
containing the output as it would appear in the Command Window.
Note
Security Considerations: Before calling
evaluateAndCapture
with untrusted user input, validate the input to avoid
unexpected code execution. Examples of untrusted user input are data from a user you might
not know or from a source you have no control over. If you need to address this concern,
consider these approaches:
Validate inputs to
evaluateAndCapture
. First, search for allowed operations. Then, if you find other operations, disallow execution.Replace
evaluateAndCapture
with an alternative. For more information, see Alternatives to the eval Function.
Performance Considerations: In most cases, using the
evaluateAndCapture
function is less efficient than using other MATLAB® functions and language constructs, and the resulting code can be more
difficult to read and debug. Consider using an alternative to
evaluateAndCapture
.
[
returns a string containing the output as it would appear in the Command Window and assigns
the outputs from the evaluated expression to the specified variables.outputDisplay
,output1,...,outputN
] = evaluateAndCapture(w
,expression
)
Examples
Input Arguments
Output Arguments
Limitations
The input expression cannot use the functions
diary
,more
, andinput
.Avoid using
evaluateAndCapture
recursively to evaluate an expression. Doing so might result in unexpected behavior.If you use
evaluateAndCapture
within an anonymous function, nested function, or function that contains a nested function, the evaluated expression does not create any variables.
Tips
To allow the MATLAB parser to perform stricter checks on your code and avoid untrapped errors and other unexpected behavior, do not include output arguments in the input to the
evaluateAndCapture
function. For example, statements likeevaluateAndCapture(w,['output = ',expression])
are not recommended.Instead, specify output arguments of the
evaluateAndCapture
function to store the results of the evaluated expression. For example:[outputDisplay,output1] = evaluateAndCapture(w,expression)
Version History
Introduced in R2025a