This submission just seems to replicate the behavior of MATLABs inbuilt functions "sprintf"/"fprintf":
A drop-in replacement for this submission can thus be easily defined in one line:
fun = @(num,dgt) sprintf('%0*i',dgt,num);
The submission is also much slower and offers much less control over the output format than "sprintf", although that error checking may be useful to someone.
I have uploaded a version that I use that does a decent amount of error checking prior to running the commands to ensure that there are no issues. It also incorporates fixes for a lot of the questions and concerns voiced here.