Feedback

How to Label a Series of Points on a Plot in MATLAB

Hello. This is Doug at the MathWorks filming video number 239 about labeling points on a plot. I'm going to go over the answer given by Amro on Stack Overflow about this very question. Let's look at the results of his code.

You can see here that we have a bunch of points, 10 of them, and they're labeled sequentially. How was that done? One of the best ways to understand code that's out there is to run it line by line, but sometimes the code is a little bit too complicated, because there are nested functions within functions. So I'm going to take this and tear it apart a little.

What does this line here do that creates the labels? I like to start at the inside and work my way out. So let's grab this. Evaluate selection. And we can see that that creates a vector of numbers 1 through 10. Next, if we take the num to string around that, we can see that we get those as a number, or actually, if we do whos ans, we can see that that is a character array 10 by 2.

Finally, we come here, and we can see that now, we have a cell array of all those strings. Perfect. Now, understanding what labels is, and how we got there, we can run these first few lines of code. And that gives us our data points.

And finally, we can pass in those values to text, telling the vertical alignment and horizontal alignment. And there we go. You can see that with Amro's answer, he was able to cleverly label all of these points without having to do a for loop. Thank you.

Product Focus

Recorded: 30 May 2012