Nice sprintf syntax using \ (left divide)
Editor's Note: This file was selected as MATLAB Central Pick of the Week
If you are like me, you use sprintf extensively in matlab coding. When you learned python, you became jealous of the nice built-in printf interpolation operator in python (%).
This achieves the same in matlab, by overloading the cell array \ operator.
Old:
>> sprintf('%s %.2f', 'hello', pi)
New:
>> '%s %.2f' \ {'hello', pi}
See SPRINTF for documentation on the meaning of the format string
Notes:
To install: unzip and save this file "@cell/mldivide.m" on your path. (@cell applies this operator to the cell array class.)
I chose to overload the cell array function because the binary operators for the cell-array type are very sparsely defined. Furthermore, cell array brackets are natural here - the '\' operator has very high precedence, so if there is really any kind of math expression to be interpolated, it would likely have to be in some form of parenthesis anyway. The cell-array {} is a simple kind of parenthesis in this case. Finally this enables one single overloaded function to handle all variable types being interpolated.
An error is thrown if the arguments do not adhere to "fmt \ {args}", where fmt is a character string. No attempt is made to call to a builtin cell-array mldivide, as presently (Matlab 2012b) there is no such thing.
Cite As
Will Fox (2024). Nice sprintf syntax using \ (left divide) (https://www.mathworks.com/matlabcentral/fileexchange/42088-nice-sprintf-syntax-using-left-divide), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform Compatibility
Windows macOS LinuxTags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.