%% New in r2021a: Capture disp output as a string
% Author: Adam Danz
% March 15, 2021
% https://www.mathworks.com/matlabcentral/highlights
%
% We've all been there.  You've got some kind of output that displays perfectly in the command window and you just want to capture that display in a string so you can use it again somewhere else.  Maybe it's a multidimensional array, a complex table, a structure or a fit object that perfectly displays the information you need in a neat and tidy format but when you try to recreate the display in a string variable it's like reconstructing the Taj Mahal out of legos.
% Enter Matlab r2021a > formattedDisplayText()
%
% Use str=formattedDisplayText() in the same way you use disp() except instead of displaying the ouput, it's stored in a string as it would appear in the command window.
% Additional name-value pairs allow you to
% Specify numeric format
% Specify loose|compact line spacing
% Display true|false instead of 0|1 for logical values
% Include or suppress markup formatting that may appear in the display such as the bold headers in tables.
%% Demo: Record the inputs and results of a polynomial curve fit

load census
[fitobj, gof] = fit(cdate,pop,'poly3','normalize','on')

%
% Capture the input table, the printed fit object, and goodness-of-fit structure as strings:

rawDataStr = formattedDisplayText(table(cdate,pop),'SuppressMarkup',true)
fitStr = formattedDisplayText(fitobj)
gofStr = formattedDisplayText(gof)

%
% Combine the strings into a single string and write it to a text file in your temp directory:

txt =  strjoin([rawDataStr; fitStr; gofStr],[newline newline]);

% Write to text file
file = fullfile(tempdir,'results.txt');
fid = fopen(file,'w+');
cleanup = onCleanup(@()fclose(fid)); 
fprintf(fid, '%s', txt);
clear cleanup

% Open text file (in Windows)
winopen(file)
% Delete demo file
% delete(file)

%
%
%