function charcell = mtx2charcell(mtx,fmt)
%charcell = mtx2charcell(mtx)
% Converts a matrix of numbers into a cell array of strings of the same
% dimensionality as MTX.
%charcell = mtx2charcell(mtx,fmt)
% Uses the format string FMT (see SPRINTF for details).
%
%This function serves as a shorthand for using the built-in NUM2CELL,
%NUM2STR, and RESHAPE commands together (thanks Urs Schwarz!)
%
%EXAMPLES:
% mtx2charcell([0 1 2]) --> {'0.000000', '1.000000', '2.000000'}
% mtx2charcell([0 1 2], '%d') --> {'0', '1', '2'}
%
%This function can be handy to use in conjunction with the author's JOIN
%function (also available on Matlab Central). For example,
% join('-', mtx2charcell([0 1 2], '%d')) --> '0-1-2'
%
%CHANGES:
% 2006-02-18: removed boilerplate copyright
% 2006-02-16 6pm: even better performance enhancement, thanks to Urs Schwarz
% 2006-02-16 afternoon: performance enhancement thanks to Jiro Doke.
%
%
%by Gerald Dalley
if (nargin < 2), fmt = '%f'; end
% Original (slow) implementation
%charcell = cell(size(mtx));
%for i=1:numel(mtx)
% charcell{i} = sprintf(fmt, mtx(i));
%end
% Better implementation suggested by Jiro Doke
%dlm = sprintf('\1');
%charcell = reshape(strread(sprintf([fmt dlm], mtx), '%s', ...
% 'delimiter', dlm, 'whitespace', ''), size(mtx));
% Even better implementation suggested by Urs Schwarz. Note that we use
% the more advanced version of NUM2CELL along with RESHAPE to avoid some
% odd ways of having the strings chopped up.
charcell = reshape(num2cell(num2str(mtx(:), fmt), 2), size(mtx));