"Peter Lessing" <
pete.l...@noaa.gov> wrote
> This is driving me crazy that you cannot control field width in the fprintf.
Peter, you are not the first person to be driven to distraction trying to use c style formatting codes, especially in a GUI where the conversion must fit into a fixed spaced field. Wouldn't it be nice if there where a format code that said "just be smart about it and do the best you can while limiting yourself to "n" characters". Of course it should be smart enough to decide when shifting over to exponential notation is going to be an improvement rather than a distraction. The c formatting codes don't get you even close and as you have noticed you can't even limit the field width if the range of input numbers is sufficiently wide. No matter what parameters you apply to either the f,e, or g formats, sooner or later you are going to be quite annoyed at the way matlab formats the number to appear in your GUI. Fortran formatting is somewhat better, but still not quite smart enough to always
do what you want. (Fortran formatting also had "repeat counts" a concept sadly missing from c format conversions).
A decade or so ago I said to myself, enough is enough ... we actually need a DWIM or DWIW formatting code (Do What I Mean/Want) so I designed one for Matlab. Actually I designed four new formatting codes (%V, %W, %v, %w) although the last one (%w) is the one that I usually use for GUIs. This has been available for a long time on the file exchange, although perhaps unfortunately it is included as part of a large package, which is why almost nobody knows about it.
To find the package, just search for "plt" on the file exchange. This package has lots of useful stuff in it, but if all you are interested in is the new DWIW formatting codes, just extract these 3 files from the package:
prin.m (this is a replacement for matlab's sprintf and fprinf functions)
Pftoa.m (called by prin.m - actually implements the new formatting codes)
prin.pdf (this is the most important file, since it explains the whole idea in detail).
Although you could call Pftoa directly, it is usually more concise and consistent to use prin().
And by the way, there is nothing that sprintf() or fprintf() can do that prin() can't do!
Another neat thing about prin() is that it brings back the repeat counts that only us old time fortran programmers miss - but even the younger guys who have never seen a line of fortran will come to appreciate repeat counts once you have them. And finally, prin() adds some functionality relating to the way it handles cell arrays. Once you take advantage of this capability, I trust you will agree that sprintf should have had this functionality from the day the Mathworks added the cell array data structure to the language.
~Paul