File Exchange

image thumbnail

Nice sprintf syntax using \ (left divide)

version 1.2.0.0 (2.02 KB) by Will Fox
Overload the cell array '\' operator to have nice syntax for sprintf

0 Downloads

Updated 05 Jun 2013

View License

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 (2020). Nice sprintf syntax using \ (left divide) (https://www.mathworks.com/matlabcentral/fileexchange/42088-nice-sprintf-syntax-using-left-divide), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (0)

Updates

1.2.0.0

Clean up MacOSX files from .zip

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