evalc
Evaluates code and returns its printed output as text instead of showing it.
Category: Programming > Programming Utilities
Syntax
T = evalc(expression)
Runs expression and returns everything it would have printed as a character vector.
T = evalc(expression, catchExpr)
Runs catchExpr if expression raises an error, and captures its output too.
Description
Everything that would appear in the command window, such as disp output, unsuppressed results and warnings, is collected into T. Variables created by the code still land in the caller's workspace. Typical uses are capturing the display of an object to put it in a label or a log, and testing what a function prints.
The captured text ends with a newline for each printed line, so apply strtrim when comparing.
Input arguments
expression- Text with the code to run.
catchExpr- Text with code to run if
expressionfails.
Output arguments
T- Character vector with the captured output, including line breaks.
Example
Capturing printed output
s = evalc('disp(pi); x = 3')
t = strtrim(evalc('disp(1); disp(2);'));
fprintf('[%s]\n', t)
Output
s =
' 3.1416
x = 3
'
[1
2]