MATLAB: How to print text from a GUI textbox to text file

guiMATLABprinttext;textwrapuicontrolwrap

I have text in a UIControl object in my GUI, and I want to print that same text to my '.txt' file. However, when I do this they look nothing alike because of the automatic text wrapping in the GUI. I am also having trouble printing a cell array of strings as this causes an error for  me. How can I print this text so it formats the same way as in my GUI?

Best Answer

You can accomplish this task using the 'textwrap' and 'fprintf' functions in a manner similar to the following example.
The 'textwrap' function will break a string into a cell array of string in order to fit within the specified UIControl object, or can be set to use a max line width. Then 'fprintf' can print this cell array of string to a '.txt' file using the syntax below:
% get string from UIControltxt = {['This is a long string from my GUI. '...
    'It appears wrapped within the UIControl '...
    'object, and should be written to a file '...
    'with that same appearance']}
% get handle from UIControlh = uicontrol('Style','Text','Position',[10 100 100 10]);
txt = textwrap(h,txt) % cell array of strings
% print to file, one string per linefid = fopen('myTest.txt','wt');
fprintf(fid, '%s\n', txt{:});
fclose(fid);