Skip to Main Content Skip to Search
File Exchange
MATLAB Newsgroup
Link Exchange
  Blogs  
 Contest 
MathWorks.com

Doug’s Pick of the Week

July 22nd, 2008

MATLAB Basics: Adding a toolbar to a GUI

People often make their own GUIs in GUIDE and they have a data visualization. When you embed an axis in your own GUI rather than using a figure window, you lose the built in toolbar that has zoom, pan, and other goodies. You can add the widgets you want back into your GUI very easily, or even make your own custom tools for the toolbar. This short video shows you how.

Video Content

iconFiles.jpgiconPod.jpg

July 18th, 2008

Miles Toolbox

Bob's pick this week is Miles Toolbox by Brian Bagenstose.

Check this out. Brian combined his interest in the travel industry with his passion for MATLAB to create a toolbox for frequent flyers. I could have really used this when I was an Application Engineer. I traveled all over to meet MathWorks customers. My wife and I certainly enjoyed that free Hawaii vacation last year. (Seriously, it's a perk. If that sounds like a sweet gig, we have openings so send me your resume.)

Even though I'm a seldom flyer now I can still appreciate this submission for other reasons. Brian's published description is a best practice. I like how he used different web data sources, and I love the overlay maps.

How have you used MATLAB to solve similar problems? Tell us about it here.


Get the MATLAB code

Published with MATLAB® 7.7

July 14th, 2008

Puzzler: Overlapping rectangles

Today’s challenge is one where you need to figure out if two rectangles have a non-zero area of overlap.

The rectangles will be specified as follows:

puzzlerrect.jpg

Just fill in your part of the code until you get the binary variable overlap defined.

ax = sort(rand(1,2));
ay = sort(rand(1,2));
bx = sort(rand(1,2));
by = sort(rand(1,2));

clf
rectangle('position',[ax(1) ay(1) diff(ax) diff(ay)], 'edgecolor', 'r')
hold on
rectangle('position',[bx(1) by(1) diff(bx) diff(by)], 'edgecolor', 'k')
axis equal

%your code here

overlap = %1 for overlap, 0 for non-overlapping

When you post your code in the comments, please use the tags


<pre> <code>

all the code so someone can just copy and paste it from the comments.

</code> </pre>

My solution is already posted.

July 10th, 2008

A Template Saves You Time

Jiro's pick this week is NEWFCN by Frank González-Morphy.

We all have our own style of writing functions in MATLAB. I've adopted a convention that is similar to the "best practice" that The MathWorks uses for the shipping m-files.

     function out = myPlusFcn(varargin)
     % MYPLUSFCN  Adds matrices
     %   OUT = MYPLUSFCN(A, B) adds matrices A and B.
     %   OUT = MYPLUSFCN(A, B, C, ...) adds all the matrices
     %         provided. All of the matrices must be either
     %         the same size or mix of same-sized matrices
     %         and scalars.
     %
     % Examples:
     %   out = myPlusFcn(1:3, 5);
     %
     %   out = myPlusFcn(2, eye(3), rand(3), magic(3));
     %
     % See also PLUS, SUM.
        <code starts here>
  • There is the function definition line.
  • The first comment line is the H1 line used by commands like lookfor.
  • The rest of the comment block is the help text.
  • I try to include a few examples of calling the function.
  • "See also" entries help guide users to similar functions.

You can read about them here.

If I always create my functions this way, why not have a template for this. This is where NEWFCN by Frank comes into play. With this, you can have a head start on creating new functions. He has it customized for his own style, so when you run

newfcn('myfcn')

it generates this m-file and opens it up in the editor:

     function myfcn()
     % MYFCN ...
     %
     %   ...
     %% AUTHOR    : Frank Gonzalez-Morphy
     %% $DATE     : 17-Jun-2008 15:53:25 $
     %% $Revision : 1.00 $
     %% DEVELOPED : 7.6.0.324 (R2008a)
     %% FILENAME  : myfcn.m
     disp('!!!You must enter code into this file <myfcn.m>!!!')
     % Created with NEWFCN.m by Frank González-Morphy
     % Contact...: frank.gonzalez-morphy@mathworks.de
     % ===== EOF ====== [myfcn.m] ======

What's nice about this is that some of the text are dynamically created, such as the file name, date, and the version. For those of you with different coding styles, his function is easy to understand so it shouldn't take much time to modify it.

As an extra nugget of knowledge, you can also create a new function m-file with a basic template directly from the Current Directory Browser, but it's not as comprehensive as Frank's.

Comments

I think laziness fuels innovation. And I mean this in a good way! Thanks for writing this, Frank. How do you use MATLAB to reduce your day-to-day work load? Tell us here.


Get the MATLAB code

Published with MATLAB® 7.6

July 7th, 2008

Advanced MATLAB: Class system for OOP in MATLAB introduction

This week we will be looking at the MATLAB class system. This video does not cover the “why” of doing OOP (Object Oriented Programming) in MATLAB. It just covers a very simple example of doing OOP.

The ten minute video shows an implementation of Conway’s Game of Life in MATLAB with classes. Though it is not covered in the video, you can implement other lifelike Cellular Automation algorithms by altering the parameters for survival and birth.

iconFiles.jpgiconPod.jpg

July 3rd, 2008

Puzzler: Data exploration solution

This was a fun little puzzle. I wonder how many people got to the first image, but did not continue to the real solution!

Contents

Load the data and take a first look

load puzzler.mat
plot(c,'.')

What is this stuff?

There is a lot of data, ranges from ~0 to ~255. Makes me think it is an image that has been made into a vector. How many different ways can this data be reshaped into a matrix?

dimensions = factor(numel(c))
dimensions =
   419   557

Reshape it!

What 'luck'! There is only one pair of prime factors. Makes you think this is the right path.

d = reshape(c, dimensions);
imagesc(d)
colormap(gray)

Tricky one.

We are on the right path, but not there yet. Those values were suspicious. Why were there decimal parts for an image. Let's look at the decimal parts.

e = rem(d,1);
imagesc(e)

There is pattern here

This is the right path, there is pattern here

f = e(:);
plot(f,'.');

Lets try the other reshape

There are two possible reshapes, try the other

g = reshape(f, fliplr(dimensions));
imagesc(g)

This is it

Now just clean it up a little

h = rot90(g, -1);
imagesc(h)


Get the MATLAB code

Published with MATLAB® 7.6

July 2nd, 2008

Puzzler: Data exploration

This is a puzzler without explanation. Brett got it in about five minutes, some of the other folks wandering near my office got it in just under 20.

The data to explore.

Remember to use the <pre><code> and </code></pre> tags around your code in the comments.


First solution in my mailbox as instructed was exactly an hour later. Have fun playing with it still. Congrats to Arthur for the win!

June 30th, 2008

MATLAB Basics: Interpolating data with interp1

This short video shows how you can take a sparsely sampled sine wave and use interp1 to interpolate the missing data points. Different interpolations such as linear, spline and nearest are all shown. Some people would consider this to be curve fitting to some degree.


Video Content

iconFiles.jpgiconPod.jpg

June 27th, 2008

Atomic clock + alarm challenge

Bob's pick this week has a twist.

Contents

The challenge

Last week Brett's pick was a MATLAB alarm clock. But an alarm is only as good as the clock behind it. Your mission, should you accept, is to hook up the alarm to an atomic clock!

The pick

"How?" you might ask. That's where this week's pick comes in. Java Time by Scott Burnside is your other building block.

The catch

Scott's motivation was a Java example, so his MATLAB GUI does the deed using Java code and data types.

I suggest excising the portion of his code that fetches the time. Build a wrapper function to return that time value as a datenum for example.

The incentive

Submit your atomic alarm clock to the file exchange and it might just become our next "Pick of the Week." Good luck!

Talk to us

If you have questions or comments about this challenge, tell us about it here.


Get the MATLAB code

Published with MATLAB® 7.6

June 24th, 2008

Puzzler: Six card poker

Update: This solution was found faster than expected. I have replaced the original with a stronger solution that I was holding in reserve. Congrats to DanK for solving the original ( found here in a zip). The contest is still running with the upgraded computerHand.p


I have been known to play the occasional hand of poker, so I have this poker-inspired challenge. I made up a simple poker type of game. The deck consists of 16 cards, four each of the values 1-4. Each player is dealt six cards.

cards1.JPG

Once you have the cards, you set three hands: High (3 cards), Middle (2 cards), Low (1 card). Each of these is scored differently. High hand is ranked by the sum of the cards. In the Middle hand largest pair wins. Pairs beat non-pairs, then high card wins in un-paired hands, ties broken by second card. In the Low hand, high card wins.

cards2.JPG

Lets look at two examples with the same cards. Notice the right hand player loses or draws depending on his strategy.
cards3.JPG

cards4.JPG

You should be able to see that the right hand player could have won also!

Each hand is worth 1 point for a win, 0.5 for a draw. Win more than 1.5 of the three total points per round for the win.
cards5.JPG

I coded up a good, but simple strategy. I am confident that someone can make a strategy that will consistently win. Free MATLAB t-shirt for the first to come up with it.

Modify humanHand.m and submit it in its entirety in the comments.


function [high, middle, low] = humanHand(hand)
% Make a valid, random hand for the human
% hand will consist of six random 'cards' selected from
% [1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4];
%
% Create three hands to be judged against the computer
% doing the smae with six other cards selected from the remainder
% of the above deck.
%
% HIGH hand consists for three cards.  The value of
% the hand is the sum of the cards.  Higher is better.
%
% MIDDLE hand consists of two cards.  Any paired hand beats any non-paired hand.
% If the competeing hands are both paired, highest pair wins.  If the
% competing hands are not paired, then the highest card in each hand
% determines winner.  If highest cards are the same, second highest cards
% are compared.
%
% LOW hand consists of a single card.  Highest card wins.
%

% This is a terrible plan that makes random hands.

randomIndex = randperm(numel(hand));

hand = hand(randomIndex);

high   = hand(1:3);
middle = hand(4:5);
low    = hand(6);

Here is the code to run the contest: (No need to modify this code)


function humanPerWins = main(numPlays)

numCardsInDeck = 16;
numCardsInHand =  6;

for i = 1:numPlays;
deck = ceil(randperm(numCardsInDeck)/4);

hand.computer = sort(deck(1:2:numCardsInHand*2 - 1));
hand.human    = sort(deck(2:2:numCardsInHand*2    ));
hand.deck     = sort(deck(numCardsInHand*2 + 1:numCardsInDeck));

[highC, middleC, lowC] = computerHand(hand.computer);
[highH, middleH, lowH] =    humanHand(hand.human);

humanScore(3) = compareHigh  (  highH ,   highC);
humanScore(2) = compareMiddle(middleH , middleC);
humanScore(1) = compareLow   (   lowH ,    lowC);

humanFinal(i) = compareLow(sum(humanScore), 1.5);

end

clf
hist(humanFinal); ylim([0 numPlays])
clc
humanPerWins = sum(humanFinal)/numPlays * 100;

disp(['Your score against the computer: ' num2str(humanPerWins) '%.'])

function score = compareHigh(H, C)

if sum(H) > sum(C)
    score = 1;
elseif sum(H) < sum(C)
    score = 0;
else
    score = 0.5;
end

function score = compareMiddle(H, C)

pairH = (H(1) == H(2));
pairC = (C(1) == C(2));

score = compareLow(pairH, pairC);

if score ~= 0.5 %is pair vs non-pair
    return
else %is non-pairs or pairs

    H = sort(H);
    C = sort(C);

    highH = H(2);
    highC = C(2);

    score = compareLow(highH, highC);

    if score ~= 0.5
        return
    else
        lowH = H(1);
        lowC = C(1);

        score = compareLow(lowH, lowC);
    end
end

function score = compareLow(H, C)

if H > C
    score = 1;
elseif H < C
    score = 0;
else
    score = 0.5;
end

Remember to use the <pre><code> and </code></pre> tags around your code in the comments.

The p-coded file that dictates the computer strategy is: computerHand.p

You can find all three files here.


Some interesting notes: My strategy against itself is about 50% win rate (of course). I tried several strategies, and used the best one overall. However, for any given “hand vs hand” one of the “lesser” strategies would beat mine. I think a blended strategy that chooses from many strategies based on the cards will win.


Doug Hull is an Application Engineer at The MathWorks. A MATLAB user since 1994, he gets paid to live, eat, and breathe MATLAB! This blog is dedicated to promoting the File Exchange by highlighting files and original video content.



  • Billigflüge: I understand from previous guys but why if statements are so slow, I just want to know if it is some...
  • alexander valdenegro: Dear Doug I have created a function with guide to transform a excel file to another format I...
  • Sharina: Hi Doug, This proves to be an excellent video. But can u please tell the version of MATLAB which has a...
  • Everest: Thanks Doug! The problem is solved now.. Actually I’ve used UserData property to gave the name to my...
  • Jon: Thanks Scott, I will probably send you an email. Basically what’s hard for me is wading through the syntax...
  • Scott Hirsch: Jon - You definitely seem to be on the right track. I’ve been working with others here in MATLAB...
  • Daniel Armyr: Nicey nice. Another feature which isn’t so important you break your skull finding yourself, but...
  • Jon: Hi Doug, thanks for your video about reading an Excel file from Matlab. I am pretty new to Matlab but I have...
  • Daniel Armyr: And here it is: http://www.mathworks .com/matlabcentral/f ileexchange/loadFile .do?objectId=2069...
  • Keerthi Nagaraj: Hey Doug, My question follows the previous post here. I am trying to edit the cells of a table. It...

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

Related Topics