Archive for January, 2008

blog

What Goes on Inside Blinkdagger?

inside_blinkdagger.gif
Photo by exploding dog

If you have ever had any experience blogging, then you would know that it can be a challenge to constantly come up with new, exciting, and valuable content for your readers. At blinkdagger, we are not the exception.

Everyday, Daniel and I are constantly talking about what kind of material we can bring to our readers. We try to figure out what readers want to see and what they might be interested in. After that, we sit down and try to come up with a plan of attack. Inside blinkdagger, we are constantly scheming, collaborating, and planning. We have so many ideas we want to implement, but of course, the limiting factor is TIME. Although we plan to continue updating frequently, there may be some periods wherein we won't be able to post for a couple days, so we just want to ask our readers to not be discouraged!!! We're working on some great things that include:

  1. A NEW theme!!! The theme we are currently using was plucked off some free wordpress theme site when we first started. It's doing a good job right now, but eventually, we want to move on to bigger and greater things. Since we are planning on designing the theme from scratch, it's not going to be easy! We know this can be quite difficult and time consuming, but we're determined to deliver the new look soon!
  2. More Matlab tutorials! Currently, we're taking some time to step back and organize the content we want to present. The next set of Matlab tutorials will deal with signal processing/ fourier analysis material. In the meantime, we plan to present smaller Matlab tutorials to keep your Matlab appetite in check.
  3. New blogging material/ideas. We constantly discuss how we can improve the content we present to our readers as well as contests that we can run.

Also, if you guys have any requests on tutorials that you would like to see, or just general feedback, you can easily contact us through the contact form. We appreciate any and all feedback!!

MATLAB

How Long Does it Take to Run Your Code?

Matlab Logo Wouldn't it be nice if you have a stopwatch to time how long your code runs for? If you ever need more than just an eyeball estimate with a regular clock, take advantage of the matlab's stopwatch: tic and toc.

Simply put tic before the first line of your code, and end the m-file with toc.

tic     % start time
%---operations---
x = 0;
for i = 1:10000
x = x+1
end
%----------------
toc    % stop time

You will get an elapsed time result

Elapsed time is 0.000040 seconds.

Advanced, GUI, MATLAB

Matlab GUI Tutorial - Mapping a Keyboard Button to Execute a GUI Callback

Introduction

Matlab Logo This tutorial will teach you how to map a keyboard press to execute a GUI callback. We will start with a basic adder GUI. Originally, the GUI adds the two numbers together when the user clicks on the "add" button. We will modify the GUI so that the two numbers will add when the user presses the "enter" key. For more information on this topic, visit this post on Adding Shortcut keys / Hot keys to a GUI.

Adder GUI

Example: Modifying the Adder GUI

  1. First, download the Adder GUI source files here.

  2. Next, we want to add the following line in the opening function:

    %we must define the KeyPressFcn for the edit text boxes or else the
    %enter key will not register while the edit text box is active
     
    set(handles.figure1,'KeyPressFcn',@myFunction); 
    set(handles.input1_editText,'KeyPressFcn',@myFunction);
    set(handles.input2_editText,'KeyPressFcn',@myFunction);
  3. Next, we want to add the following code at the end of the m-file

    function myFunction(src,evnt)
    %keyPressFcn automatically takes in two inputs
    %src is the object that was active when the keypress occurred
    %evnt stores the data for the key pressed
     
    %brings in the handles structure in to the function
    handles = guidata(src);
     
    k= evnt.Key; %k is the key that is pressed
     
    if strcmp(k,'return') %if enter was pressed
        pause(0.01) %allows time to update
     
        %define hObject as the object of the callback that we are going to use
        %in this case, we are mapping the enter key to the add_pushbutton
        %therefore, we define hObject as the add pushbutton
        %this is done mostly as an error precaution
        hObject = handles.add_pushbutton; 
     
        %call the add pushbutton callback.  
        %the middle argument is not used for this callback
        add_pushbutton_Callback(hObject, [], handles);
    end
  4. And that's it. Run the GUI and verifies that it works.

Download: Source Files

You can download the source files here.

This is the end of the tutorial.

blog

Is Work Taking Over Your Life?

overworked
Photo by chaparral

"Work, play, sleep. Choose two."

When I first arrived as an unsuspecting frosh toHarvey Mudd College (one of the toughest engineering schools around) , the previous quote was continually tossed around by the older students and professors.

As I quickly came to realize, this quote was no joke! The Harvey Mudd coursework was such an overwhelming beast that you could sometimes hear the lesser students whimpering "uncle" in the middle of the night. I reckon that Mudd is not the only place where work reigns supreme. In fact, the pressures and tension of a real-life work environment can rival or even surpass the torture chamber that I experienced at Mudd (though I highly doubt this). So what I'm about to discuss applies to a good majority of people.

The majority of the students at Mudd fell under the work/sleep category. Students would typically work hard throughout the day, allowing them to get a good night's rest. The next day, they would be duly rewarded with 5 new problem sets due the next day. Not the best existence, but it was preferable to failing out of school. Similarly, many of us go to work from 9-5, go home and make dinner, and go straight to bed. Rinse and repeat x 5.

The Solution

So how did students prevent themselves from becoming crazy? All work and no play calls for some very depressed and burned out students. Many of the students learned very quickly that it required a delicate balancing act to survive at Mudd. The key to survival here was flexibility.

While WORK would always predominantly take up the largest slice of the pie at Mudd, there was still an oppurtunity for clever juggling and manipulation of the rest of your time. For example, you might sleep a little later than usual to catch a movie that you've been wanting to watch. You might be sleep deprived for a little bit, but you can catch up on your sleep at some other time. Take another example,you miss a couple of classes to go on that vacation you've been dreaming about. You might be behind in some of your classes when you come back, but you can copy off your friend's notes and get back up to speed. Other times, you might have SO much work to do that you have to pull consecutive all-nighters. It's all a balancing act that takes good judgement and requires a good sense of responsibility to maintain.

Obviously, you don't want to go on vacation during finals week. :P

So while it is true that you can only choose two things among work, play, and sleep, it is important to realize that it is not set in stone. Be flexible, be dynamic. Mix it up, keep things interesting.

Daniel Sutoyo recently wrote a post on a similar topic over at worknplay.net that can be found here. It's an interesting post that deals with how to effectively balance work, play, and sleep for a variety of different personalities.

MATLAB

Matlab - Harnessing the True Power of Matlab through Vectorization

Introduction

Matlab Logo One of the main advantages of Matlab are vectorized functions, which are functions that can be performed on an entire array as if the function was applied to every individual element within the array. In low-level programming languages, the best way to perform an operation across an entire array is to use a FOR loop. In Matlab, the use of vectorized functions allow you to do the same thing without using FOR loops. For people who have experience with traditional programming languages like java and C++, vectorization may not come naturally. This tutorial will explain the advantages of using vectorized code and will provide some examples.

Why Use Vectorized Code?

Advantages

  • Increased Speed: Vectorized code runs significantly faster. How much faster? This depends on the commands used and the application. And although Matlab has made great strides in accelerating low-level code, vectorized code still runs faster. But in general, vectorized code is faster than it's low-level counterpart.

  • Compact: Vectorized code is more compact and can be easier to read and understand.

Disadvantages

  • Difficulty: Most people with programming experience are used to doing things in a low-level manner (i.e. FOR loops). Vectorizing code can be a challenge because of the different thinking that is required. In addition, there is no set formula on how to vectorize code. A good working knowledge of the available functions within Matlab is certainly helpful when it comes to vectorization.

  • Compact: Being compact is both a blessing and a curse. Vectorized code can be difficult to understand because it is so compact. If the code is undocumented and does not have any comments, it can be a real pain to figure what the code does.

Two Simple Examples of Vectorizing Code

  1. Let's say that I wanted to square all the elements within an array. If I wanted to do it the low-level method, I would use the following code in Matlab.

    x = [ 1 2 3 4 5 ];    % vector of values to square
    y = zeros(size(x));  % initialize new vector
    for i = 1 : length(x) % for each index
    y(i) = x(i)^2;         % square the value
    end                      % end of loop

    Conversely, I can do the same thing with vectorized code.

    x = [ 1 2 3 4 5 ]; % vector of values to square
    y = x.^2; % square all the values (notice the dot before the operator!)

    I think we can all agree that the second method is much easier! Lets look at the next example.

  2. Lets say we want to multiply two arrays together, element by element. So for example, if we have the following two arrays:

    a = [1 2 3];
    b = [6 5 4];

    we want to multiply it so that we get:

    c =[6 10 12];

    We can use the following code to accomplish that instead of using a FOR loop:

    c = a.*b; %once again, notice the dot before the *

An Example of the Speed Increase using Vectorized Code

Let's compare the time it takes to process the following two snippets of code. The first is the non-vectorized version.

myVector = 1:100000; %row vector that goes from 1 to 100000
for x=1:length(myVector)
    if(mod(myVector(x),2))  %if the element is even
        myVector(x) = cot(myVector(x)); %we take the cotangent of it
    end
end

The second version is the vectorized code

myVector = 1:100000; %row vector that goes from 1 to 100000
indexTrue = mod(myVector,2)==1; %get the indices of elements that are even
myVector(indexTrue) = cot(myVector(indexTrue)); %take the cot of even elements

Using the profile command, we can do a quick time analysis on how long each snippet of code took to run. As it turns out, non-vectorized code ran in about 1.2 seconds. The vectorized code ran in about 0.03 seconds. This makes the vectorized version run 40 times as fast! As can be seen, there can be quite a dramatic speed improvement!

More Examples of Vectorized Code

  1. Given a vector, we want to add 10 to each element that has a value greater than 5. Here's how it would be done using a low-level method:

    myVector = 1:10; %row vector that goes from 1 to 10
    for x=1:length(myVector)
        if(myVector(x) > 5)  %if the element is greater than 5
            myVector(x) = myVector(x) + 10; %we add 10 to it
        end
    end

    Here is the vectorized equivalent:

    %use logical indexing to figure out which elements are greater than five
    logicalIndex = myVector > 5;
    %add 10 to the elements greater than 5
    myVector(logicalIndex) = myVector(logicalIndex) + 10;
  2. Given a 4x4 matrix, we want to cube each element and then sum up all of the elements within the matrix. The following vectorized code can accomplish that.

    myMatrix = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16];
    total = sum(myMatrix.^3);
  3. Given a vector of data, we want to normalize the data to the largest data point. The following vectorized code can accomplish that.

    myVector = [3 4 5 1 4 6 3 4 1 10 8 9]; %example vector
    maxValue = max(myVector) %first get the largest value in the vector
     
    % divide the example vector by the max value to normalize
    normalizedData = myVector/maxValue
  4. Given a set of 3d data points, we want to find the average distance from the origin for each 3d point. The following vectorized code can accomplish that.

    xVector = [1 2 3 4 5];
    yVector = [3 4 5 6 1];
    zVector = [4 5 -3 2 1];
    distanceVector = sqrt(xVector.^2 + yVector.^2 + zVector.^2);
    averageDistance = avg(distanceVector);

Helpful Functions for Vectorization

Most of the standard functions are vectorized, but there is no clear cut recipe on how to go about vectorizing code. You will certainly get better at it with practice.

  1. arithmetic operators: +, - , .* (array multiply), ./ (array divide), .^ (array power), etc

  2. relational operators: ==, >, <, etc

  3. logical operators: & (and), | (or) , ~ (not), etc

  4. trigonometric functions: sin, cos, tan, asin, and so on.

  5. Other helpful functions: find, sort, abs, and many more.

Parting Note

Although vectorization can make your code simpler at times, it can also make your code archaic and difficult to understand. In addition, it can be difficult to vectorize your code at times, so it may not be worth the time and effort to do so. Thus, you may be wondering if it is really worth your time to vectorize your code. If you find it too difficult to vectorize your code, you may be better off just using a low level method. The most important thing is to make sure that your code works! After you get your code working, you can consider optimizing it through vectorization.

In conclusion, vectorization is not required, but it can certainly be beneficial. Unless the arrays you are dealing with are quite large (and depending on the operations performed), it can be difficult to see the benefits of vectorization. But in general, I believe that it's good practice to get into the habit of using vectorized code as it is more efficient.

You can visit this link for a more in depth look on vectorization.

This is the end of the tutorial.

Next »