Doug’s MATLAB Video Tutorials

September 18th, 2009

Revisited: Integrating to find the volume underneath a set of non uniformly spaced data

Well, am I turning red! Soon after I posted my last video about how to find the volume underneath a set of non uniformly spaced data, I found one of our developers had a better way to do it using features of the newly released MATLAB 2009b.

Here is the video again:

Let’s repeat the code here from the beginning




n = 10;
randOffset = 0.1;
h = 1;
x = rand(n);
x(1:4)=[0 1 0 1]';
y = rand(n);
y(1:4)=[0 0 1 1]';
z = h + randOffset*rand(n) - randOffset/2; %make average height
plot3(x,y,z,'.')
axis equal
zlim([0 h + randOffset])


Now, the new feature being used is the fit command from the Curve Fitting Toolbox:


sf = fit( [x(:), y(:)], z(:), 'linearinterp' )

     Linear interpolant:
       sf(x,y) = piecewise linear surface computed from p
     Coefficients:
       p = coefficient structure


Then the volume is found using more or less the same call to QUAD2D. I told you it was cool:


vol = quad2d( sf, 0, 1, 0, 1 )

vol =
       1.0038


Caveats You’ll notice that I had appended some “special points” to this data set. This is so that we can interpolate into the corners. The “fit object”, sf, will suffer the same problem as it is built on top of GRIDDATA. Another way around this issue is to use a scheme that extrapolates,

  • Use a different interpolation scheme, e.g., ‘nearest’/ ‘nearestinterp’ or ‘v4′/ ‘biharmonicinterp’ (I’d use the latter because it is the best). This will work for both fit and GRIDDATA.
  • Fit the data in a least squares sense, e.g., using ‘lowess’.
Extrapolation should be OK in this case as we are not extrapolating too far from the data.
Sometimes, I think I write this blog so that *I* can learn more MATLAB from the people that read it! Your comments and suggestions are always welcome below!

September 8th, 2009

Integrating to find the volume underneath a set of nonuniformly spaced data

This video covers the use of GRIDDATA, anonymous functions, and QUAD2D to integrate the volume under a set of randomly spaced data points. First an interpolation scheme must be put in place, then a numeric quadrature function is invoked. This video shows the creation of a good synthetic data set with a known volume to test the rest of the algorithm. A good test data set like this really give confidence in the building of your algorithm.
Here is the code that was written:
% I have a dataset "A" (n by 3) of ordered triplets [x,y,z]. 
%I want to calculate the volume between surface defined by "A" and 
%the xy plane. "A" has only positive values but is not uniformly 
%spaced and not gridded. "A" cannot be described by a simple 
%function. Any help?

n = 10;
randOffset = 0.1;
h = 1;

x = rand(n);
x(1:4)=[0 1 0 1]';
y = rand(n);
y(1:4)=[0 0 1 1]';
z = h + randOffset*rand(n) - randOffset/2; %make average height


plot3(x,y,z,'.')
axis equal
zlim([0 h + randOffset])

interpZ = @(xi,yi) griddata(x,y,z,xi,yi) %set up interpolation

interpZ(0.5,0.5) %test interpolation
vol = quad2d(interpZ,0,1,0,1) %volume should be close to 1
Note: there is an update to this post here: http://blogs.mathworks.com/videos/2009/09/18/revisited-integrating-to-find-the-volume-underneath-a-set-of-non-uniformly-spaced-data/

August 27th, 2009

Basics: Implementing a formula in MATLAB

This video will demonstrate how to implement a formula in MATLAB. In the video, we will make a function out of the formula. The function will take a scalar (single number) or a vector. We want to make the function take either a scalar or a vector so that you do not have to loop through calling the function. This is not for speed, but for the simplicity and readability of the code. This vectorization is done by means of array division ( ./ ) and array multiplication ( .* ). These operations do division and multiplication on an element by element basis.

August 21st, 2009

Basics: Code review- the thought process in rewriting code for clarity

This short video covers the thought process of rewriting some code for clarity. The six lines of code are lengthened into twice that. The code is much more readable and maintainable. The problem is not as important as the thought process, however, the problem is about reshaping a matrix.

August 14th, 2009

Puzzler: Results of most difficult puzzler yet

The “Rules of the new game” puzzler was the most difficult one yet. Puzzlers are MATLAB programming challenges that I post from time to time. They lead to interesting discussions of MATLAB coding styles. There were two very interesting submissions which I would like to highlight from T and Darren. They both made some very clever optimizations that give speed improvements over my original solution. I wrote my solution with the objectives of guaranteeing a solution and keeping the code simple.

One major thing that all solutions needed to do for this problem was to find all of the pixels that would be touched in a flood operation. I used the method developed by the community in my last puzzler. Darren’s entry used a method that padded the board around the edges, making his operations easier. It was very similar to a two dimensional convolution. It very quickly would find the “fringe” of the existing block.

T’s entry used a different technique that was more heavily reliant on the Image Processing Toolbox. Using IMDILATE and other functions, he was really able to make a good algorithm for finding the neighbors to the ever growing blob.

I used a greedy algorithm, simply choosing the color that that would cause the greatest number of squares to change color. Since this was a recursive algorithm, I would order the possible choices by greatest to least change and hopefully find an acceptable solution simply by always taking the first ranked choice. Recursion would (eventually) find a solution in the exhaustive search, so I did not look ahead any moves. I was doing a depth first search.

T and Darren would actually look ahead a few moves, choosing color that appeared best in a couple of moves (exhaustive search, since it was a more limited set). Not only this, but T wired his solution up with many configurable parameters, such as depth of search and metric to decide which is the best choice.

If you are interested, I would recommend looking at the code from T and Darren on the File Exchange.

August 6th, 2009

GUI tutorials from the File Exchange

I was once one of the many people that have been a steward of the Pick Of The Week blog. I try not to highlight File Exchange files here, but this exceptional tutorial is, well, an exception. Matt wrote a series of small, single purpose GUIs that show a simple skill. Take a look at the list of questions that he solves:

1. How do I manipulate the strings in a uicontrol?

2. How do make a uicontrol invisible/visible?

3. How do I make a multi-line editbox?

4. How can I let the user of my GUI know his actions are futile (or producing no results)?

5. How can I tell which uicontrol is selected?

6. How can I tell how many times a uicontrol has been activated?

7. How do I tell which button in a buttongroup is selected?

8. How do I let the user know a process is running in the background?

9. How do I control the mouse pointer with a GUI?

10. How can I access the value (current position) of a slider?

11. How can I use different colored strings in a listbox?

12. How can I make text that can be copied but not changed?

13. How do I allow the user of my GUI to set the range of a slider?

14. How do I use the buttondownfcn on an axes object?

15. How do I make a callback talk to another callback?

16. How can I get the string from a popup or listbox?

17. How can I set the string in a popup or listbox?

18. How can I add to the string in a popup or listbox?

19. How do I tell which figure was current before my callback executed?

20. How do I get data from another GUI?

21. How do I make a GUI to open image files only?

22. How can I make popup choices mutually exclusive?

23. How can I show the current pointer location in axes coordinates?

24. How can I use uicontextmenus?

25. How do I make my GUI control an axes in another figure?

26. What are callback strings?

27. How can I make it so that when one of the figures closes, they all close?

28. How do I make several uicontrols interact in a more complicated GUI?

29. How do I get data from a GUI to the base workspace?

30. How do I make toggle buttons act like tabbed-panels?

31. How can I make a password editbox that has the ***** symbols?

32. How can I use nested function as callbacks?

33. How can I use uiwait in a GUI?

I found it best to print out the two page PDF with questions and then run the GUIs I wanted. Download the bundle here.

July 28th, 2009

Puzzler: Rules of the new game

I was playing this game by LabPixies on my iPhone. I spent more time thinking about programming an optimal solution than anything else while playing. I decided to give it a try in MATLAB. After getting some help from the MATLAB community in the last puzzler I was able to implement a quick running solution.

I am always amazed at the creativity of the MATLAB community, so I am posting all the files needed so you can implement your own solution. I have included my solution also, but I recommend not looking until you have tried your own.

Since this is a more involved problem, posting to the comments does not seem as reasonable. Please e-mail me (hull@mathworks.com) your completed code (one file, has everything it needs to run, your contact info in the comments) and I will put together a video covering the best of ideas. If I use your code or ideas in the video, I will send you a MATLAB t-shirt.

MINOR SPOILER ALERT

What I have discovered is that this program either finds a solution very quickly, or does not find one before I get bored (5 minutes, I should run it overnight….). I take a “greedy” approach (selecting the color that will cause the largest change), this is not always optimal. I am doing an exhaustive search, only looking one move ahead. This will find a solution if it is possible, but there might be a better way.

July 24th, 2009

Modeling your Mom’s head with MATLAB

I frequent Twitter as MATLABDoug. You can check there for daily MATLAB tips in 140 characters or less, blog post announcements and other things that I find interesting.

While reading the stream of Tweets about MATLAB I found this little gem of a tweet: How to convert your Mom’s head into a 3-d model on Instructables.

This video on Instructables.com is good at showing the setup for the experiment, but does not show much about how the processing was done. They do make the MATLAB script available if you want to do this yourself. Worthy of a watch.

MATLAB scan of Mom

Do you have any fabulous uses of MATLAB that you would like to share with the world?

July 17th, 2009

Advanced: Modifying a contour plot with Handle Graphics

The contour plot will choose the colors of the contour lines based on the level of the contour. However, if you want to do something more, like change the line width or line style, you will need to do something like what follows in the video.

July 10th, 2009

Basics: Visualizing a function of two variables

I was interested in visualizing isolines on a graph of BMI. This is a non-linear function of two variables. I thought the best way to visualize this would be with a contour plot.

This video is very basic, it starts by creating the vectors of inputs to this function and then making them into matrices. We then calculate the BMI and modify the contour plot to look more like we want.


Doug Hull is a proud MathWorker who is on a mission to help you with MATLAB.

Doug's picture

These postings are the author's and don't necessarily represent the opinions of The MathWorks.