Reputation: 2059
Can someone help me create an anonymous function format_this(txt)
to format text so there's a newline character replacing a whitespace that is close to the edge of the command window - in essence 'pretty printing'? It does not have to be perfect (and in fact, doesn't need to be an anonymous function), however I couldn't find something like that oddly enough...
Here's what I have:
txt='the quick brown fox jumps over the lazy dog';
txt=[txt ' ' txt ' ' txt]; %make longer
w=getfield(get(0,'CommandWindowSize'),{1}); %command window width
space_pos=strfind(txt,' '); %find space positions
wrap_x_times= (w:w:size(txt,2))); %estimate of many times the text should wrap to a newline
format_this=@(txt) txt;
%something like an ideal output:
disp(format_this(txt)) %example for super-small window
ans =
'the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog'
Upvotes: 0
Views: 93
Reputation: 364
You need a combination of string functions to achieve that result. The program below shows how to do that.
clc
% the text
txt='the quick brown fox jumps over the lazy dog';
% makethe text a bit longer
txt=[txt ' ' txt ' ' txt];
% get the command window width
w=getfield(get(0,'CommandWindowSize'),{1});
% get the length of the text
txt_len = numel(txt);
% check if the length of text is exactly divisible
% by the size of window (w) or not
if(mod(txt_len, w)~= 0)
% if not, then get the number of
% characters required to make it a
% multiple of w
diff_n = w - mod(txt_len, w);
% append that many spaces to the end of the string
txt(end+1 : end+diff_n) = ' ';
end
% create an anoymous function
% step 1 - Split the array in multiple of size w into a cell array
% using reshape() and cellstr() function respectively
% step 2 - concatenate the newline character \n at the end of each
% element of the cell array using strcat()
% step 4 - join the cell array elements in a single string usin join()
format_this = @(txt)join(strcat(cellstr(reshape(txt,w, [])'), '\n'));
% get the formatted string as a 1-d cell array
formatted_str = format_this(txt);
% print the string to ft
ft = sprintf(formatted_str{1});
% display the ft
disp(ft)
Program Output tested with variable size of the command window.
Upvotes: 2
Reputation: 30047
For printing in the Command Window, this is a preference which can be set in the preferences pane under
HOME > Preferences > Command Window
The result can be seen with a quick test:
Upvotes: 2