MATLAB Tip of the Day: Counting in the Command Window

This is actually a two-fer: padding a number with a variable number of leading zeros or spaces and updating text in the Command Window without creating a bunch of new lines.

Variable number padding

The sprintf function includes in its documentation the instructions for padding a number with leading zeros.

myNumber = 4
paddedNumber = sprintf('%02d', myNumber)

paddedNumber =
        04

But what do you do when you don't know how many zeros you'll want to use? You need another variable. The syntax looks like this:

paddedNumber = sprintf('%0*d', numDigits, myNumber)

If I specify numDigits, I can pad myNumber with any number of zeros I choose. Of course, I need to define numDigits somehow. In the FrameCounter function below, I want to have enough leading zeros that my last frame has no zeros out front. So if my last frame is 123, I should get two leading zeros for numbers less than 10, one leading zero for numbers up to 99, and then no leading zeros for the rest. Here's how I like to do it:

numDigits = length(sprintf('d', lastNumber));

This is to say, I write out the number as a string and calculate how many characters that is (i.e. the length of the string). That's how many digits I need to do the padding. Simple.

Updating text in the Command Window

I was using a program in MATLAB that took a long time to run and had an unfortunate tendency to crash1. I wanted to know which frame it had been working on before it failed, and in general I wanted to have some idea how much progress it had made. At the time, I wasn't aware of the built-in progress bar, and then I learned that that can actually slow down whatever process it is you're trying to keep tabs on, so I wrote my own. It just printed the current frame number to the Command Window every ten frames or so, which was enough to narrow down the range of the failed frame. Every time a new frame was printed to the Command Window, though, it made a new line, and after thousands of successful frames, I had a Command Window full of numbers. What I wanted was a way to update the number in place, without printing a new line.

In 2011, I went to the CPLC Summer School at UIUC (which was pretty fun and enlightening) and I saw what I wanted in action in an analysis program. I didn't have a chance to look at the source, though, so I asked how it worked. The student I was working with said he didn't recall for sure, but he thought it had something to do with backspaces. That clue was enough for me to figure it out on my own.

Here's how it works:

  1. Print the text you want to display to the Command Window using fprintf.
  2. Print enough backspace characters (again, with fprintf) to delete each of the characters that need to change.
  3. Print the new text.

Getting it to work as a separate function took a little thinking, but turned out to be pretty simple. The result is below. I hope you find it (or its components) as useful as I have over the years.

FrameCounter

function FrameCounter(first_num, last_num, current_num, show_text)
%%  Determine the number of digits in the number
num_digits = length(sprintf('%d',last_num));
text = 'Frame ';
if nargin < 4
    show_text = 0;
end
%%  Before displaying the first number
if current_num == first_num
    if show_text == 1
        %%
        % Display "Frame " before the numbers
        fprintf(text)
    end
    for aaa = 1:num_digits
        %% Prime the counter with spaces
        fprintf(' ')
    end
end
%% Remove the previous number
for bbb = 1:num_digits
    fprintf('\b')
end
%%  Display the current number
fprintf('%0*d', num_digits, current_num)
%%  Last number
if current_num == last_num
    if show_text == 1
        char_num = length(sprintf(text));
    else %if show_text == 0
        char_num = 0;
    end
    backspaces = char_num + num_digits;
    pause(.1) % Without this pause, the last number sometimes doesn't display properly.
    %% Remove last number and "Frame " text
    for ccc = 1:backspaces
        fprintf('\b')
    end
end
end

1: The source of the crash was a read/write conflict with the Windows 7 indexing system. More on that conflict here if you're interested.

The best scientist I know

Joe Palca asked me on Twitter this morning,1

Who is the best scientist you know, and what qualities make her/him the best?

I had to think a moment about this. I'm sure many people who love science have a favorite historical scientist. My shortlist is mostly crystallographers: Kathleen Lonsdale, Dorothy Crowfoot Hodgkin, the Braggs (Sr. and Jr.), Linus Pauling,2 and I am amused by the story of Alessandro Volta, who was such a great practitioner of the scientific method, that he felt the need to zap himself with his electro-motive apparatus over and over again on various parts of the body "where the skin is very delicate" to make sure it really worked.3

Who is the best scientist you know? It's a simple enough question, but it can be interpreted in several ways. For one, what sense of "know" are we considering?

  • Who is the best scientist you know of?
  • Who is the best scientist you have seen (at a conference, seminar, etc.)?
  • Who is the best scientist you have met?
  • Who is the best scientist who knows your name in return?
  • Who is the best scientist you know personally?

Then we should consider what we mean by "best scientist"? The follow-up question (what qualities…?) allows us to define our own criteria for best, but who gets to be a scientist? Must we consider only professional scientists?

Because this question has so many variations, I have several answers. Here are two scientists I aspire to be more like.

W.E. Moerner is one of the best scientists I know. I have heard him speak on a few occasions, and I have read a fair number of his papers. My advisor was a postdoctoral fellow in his laboratory, and from comments she has made over the course of my PhD, I believe that experience has significantly influenced her approach to science and advising.

Dr. Moerner gave a seminar at UM once, and I was among the students and post-docs who ate lunch with him. We had sandwiches and chips in the Biophysics conference room, and he chatted with each and all of us about a variety of topics. Someone asked him about his work with Kador on single-molecule spectroscopy, and he jumped up to the white board and started sketching out diagrams and explaining the story. He did so clearly and carefully, and seemed to have all the patience in the world when someone didn't understand. He has a reputation for being brilliant, and that made me a bit intimidated at first, but that feeling wore off quickly. He was approachable and just plain excited to tell us about the neat things he'd learned. And he didn't just talk to us, he conversed with us.

Krishanthi Karunatilaka is one of the best scientists I know personally. She was a post-doc in our lab until last fall. She is absolutely meticulous; I have some real notebook-envy for her tidy, organized notes in clear and even handwriting. She is driven and dedicated without any of the pushiness that I have come to associate with those terms. She has worked some long, hard days because she wants to know the answers to the questions she has. She also finds balance. I know that her Saturday mornings in Ann Arbor were set aside for a peaceful cup of coffee on her apartment balcony. She doesn't get knocked down by failures. If an experiment doesn't work (or gives unexpected answers), she has another idea, she keeps rolling on. When someone else is struggling, she's the first person to say "Don't worry, you can try something else. Keep going." She has a talent for presenting even brand-new data in a way that makes it sound like she's considered their implications for weeks.

Other names come to mind as well,4 but you'd find they follow the same pattern: the best scientists I know do good, thoughtful, careful scientific work, and are also excellent teachers, communicators, and just generally nice people.

So those are my "best scientists." Who are the best scientists you know? What makes them the best?


1: I admit, I had a complete fan-girl moment.

2: I admire Marie Curie, too, but she is used so often as The Token Female Scientist, that I think of the words of Mr. Bennet: “That will do extremely well… You have delighted us long enough. Let the other young ladies have time to exhibit.”

3: From Volta's letter to the Royal Society:

If, by means of an ample contact of the hand (well moistened) I establish on one side a good communication with one of the extremities of my electro-motive apparatus … and on the other I apply the forehead, eye-lid, tip of the nose, also well moistened, or any other part of the body where the skin is very delicate: if I apply, I say, with a little pressure, any one of these delicate parts, well moistened, to the point of a metallic wire, communicating properly with the other extremity of the said apparatus, I experience, at the moment that the conducting circle is completed, at the place of the skin touched, and a little beyond it, a blow and a prick, which suddenly passes, and is repeated as many times as the circle is interrupted and restored.

4: For example, my introduction to Jenny Glusker was similar in many respects to my lunch with Dr. Moerner.

Victor DiRita, a collaborator and dissertation committee member of mine, is another one of the best scientists I know. He teaches me something every time time we meet, even if only for a few minutes.

The best amateur scientist I know is probably my uncle Tom, for lots of the same reasons. He is also the only person I know who gets really excited about moss.

Swift

I got an iPod Touch in 20091 and wished from the start that I could write my own apps for it.2 I knew approximately nothing about coding, though, so it was a rather far-away sort of wish.

In grad school I learned to code in Matlab. It was a sink-or-swim kind of thing. With the help of another grad student, two books, the wonders of Matlab Central (and later StackExchange), and lots of practice, I learned how to write and debug programs.

My brother is a programmer, and by his standards I'm a hobbyist at best, but I can make the computer do what I need, and I've gotten better as I've gone. Still, he teases me about how I should learn a "real" language, and I kind of agree. So about a year ago, after listening to a Mac Power Users episode about learning to code, I bought a book about learning Objective-C.3 I got a little better than halfway through it before other things got in the way; it's one of the things I was planning to come back to this summer between grad school and job.4

Those summer plans may have just changed, though. A week or two ago at the WWDC Keynote, Apple announced a new programming language called Swift and I think I'm in love. I watched the demo and thought "I can definitely do this." I may finally be able to write the apps I wished for. There's an eBook about the language, which I've already started reading. Though it starts from "Hello world," I don't think it would be much help if you had no familiarity with programming whatsoever,5 but it does look promising for someone (like me) who has at least dipped their toes into the programming pool before.

So that's my next side project: learn another language, try to make an app (I have several ideas), and see how it goes. I'm excited to get started.


1: Nearly 5 years later, it's a bit sluggish but still kicking.

2: I was also bowled over by the idea that the device playing podcasts in my pocket had a bigger hard drive than my laptop's original drive: 64 vs 60 GB. When I stop to think about it, it still amazes me how powerful the gadgets in my pockets and bags are. And then I start feeling old…

3: It's a really good book, too: The Big Nerd Ranch Guide. My inability to finish it has much more to do with being an overwhelmed graduate student in need of "off" time for my brain than the quality of the book. I highly recommend it, and I think it's an excellent example of instructional writing.

4: Oh yeah, I accepted a job about the same time I was completely overloaded with dissertation and defense stuff. The defense is done, the dissertation is submitted, and though I wrote about the stresses and thrills of job-hunting, I guess never did mention here that I did accept an offer. More on that another time. Short version: I have a job starting in August and I'm excited about it!

5: This is actually the same gripe I have about the Matlab Getting Started Guide and books for "beginners." All of these say that you can start from scratch, but they usually assume knowledge and vocabulary that a first-time programmer may not have. (I'm looking at you, floating-point array.)

Consider these programming languages like human languages: the Getting Started Guide might tell me how a verb is conjugated, but if I don't know what "conjugation" is, I don't know what to do with that information. If you've learned another language before, you've probably learned the meta-terminology already, and have some kind of structure for understanding this new set of words, sounds, and grammar rules.