This function lets you wrap long text strings to a specified width in characters. If no width is specified, the current width of your command window is used.
Chad Greene (2021). wraptext (https://www.mathworks.com/matlabcentral/fileexchange/53176-wraptext), MATLAB Central File Exchange. Retrieved .
I've actually made a few modifications:
* Now returns early if input string is already short enough.
* Added "|| isempty(r)" to conditional checking whether any words are
longer than the specified width.
* Now detects if LAST word is too long.
* Added word separators '/', '-'
I think there's also scope to allow for custom word separators.
Chad, if you're amenable to it, I'd be fine emailing you my new version so you can update wraptext with whichever features you think are nice. Otherwise I can just make a new File Exchange script and call it something like textwrap, or wraptext2 or whatever.
On 2020a, the conditional at line 58 fails to detect strings with no spaces. r is empty, which causes the condition to be false. To fix it, I added || isempty(r).
@Roberto, that's a clever solution and it is indeed computationally more efficient than the current implementation of wraptext. However, it is rather unintuitive, hard to remember, easy to get wrong, and doesn't allow for automatically sizing the text to the current width of the Command Window, as wraptext automatically does when users do not specify a preferred width. I haven't encountered any instances in which wraptext has been a computational bottleneck, but if I do I will certainly adopt your suggestion. Thanks!
The functionality can be easily and more efficiently implemented using string replacement with regular expression. E.g., to wrap text to 80 columns:
The script inserts a newline before the last word if the input string is shorter than the specified width. This should be easy to fix
Inspired by: strlookup
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!