File Exchange

image thumbnail

Nice sprintf syntax using \ (left divide)

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


Updated 05 Jun 2013

View Version History

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.

>> sprintf('%s %.2f', 'hello', pi)

>> '%s %.2f' \ {'hello', pi}

See SPRINTF for documentation on the meaning of the format string


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 (2021). Nice sprintf syntax using \ (left divide) (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (0)

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

Community Treasure Hunt

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

Start Hunting!