File Exchange

image thumbnail

wraptext

version 1.0.0.0 (7.08 KB) by Chad Greene
Wrap long text to a specified width.

2 Downloads

Updated 23 Sep 2015

View License

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.

Cite As

Chad Greene (2021). wraptext (https://www.mathworks.com/matlabcentral/fileexchange/53176-wraptext), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (5)

Sam Rabin

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.

Sam Rabin

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).

Chad Greene

@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!

Roberto Tron

The functionality can be easily and more efficiently implemented using string replacement with regular expression. E.g., to wrap text to 80 columns:
strWrapped=regexprep(str,'.{1,80}\s','$0\n');

Mads Kaern

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

MATLAB Release Compatibility
Created with R2012b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Acknowledgements

Inspired by: strlookup

Inspired: ecopath_matlab: A Matlab implementation of Ecopath, xkcd1930

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

wraptext/html/