Matlab: Rotating Sphere Animation

Let’s say you want to make a simple simulation of a sphere spinning in Matlab.
First, you set the pop-up window to have the title ‘Spheres,’ the window to have black background, and specify said window’s position and size.

format compact
set(gcf,'Menubar','none','Name','Spheres', ...
 'NumberTitle','off','Position',[10,350,400,300], ...
 'Color',[0 0 0]);

Matlab has a nice built in “sphere” surface function that you can invoke after you specify where you want it’s axes. Note that if you don’t include the h = axes('Position',[0 0 1 1]); command, the program will run the same except your view of the sphere will be farther away (smaller).

%Zooms in on sphere
h = axes('Position',[0 0 1 1]); 
%Draws sphere
[X Y Z]=sphere(20);
C = Z^2 + Y^2; %creates color data to map onto sphere
hs = surf(X, Y, Z, C);

The sphere function creates a “curved” surface using quadrilaterals. The boundaries of these quadrilaterals can be hidden set(hs,'EdgeColor','None'); or shown set(hs,'EdgeColor',[0.5 0.5 0.5]);

%Shows wires
set(hs,'EdgeColor',[0.5 0.5 0.5]);

%Adjusts transparency
alpha('color');
alphamap('rampdown');

%Adjusts lighting
camlight right;
lighting phong
hidden off
axis off
axis equal

Stopping here, you have a static sphere.

Depending on whether you wish to just play the animation or if you wish to also save it as an ‘.avi’ file, you approach the animation in different ways. Either way, the animation looks like this:

To play the animation without saving it:

oh=findobj(gca,'type','surface');
%Spins about z axis.
for i = 1:36
axis off;
rotate(oh,[0 0 1],10);
M(i) = getframe(gca);
end
%Spins about y axis.
for i = 1:36
axis off;
rotate(oh,[0 1 0],10);
M(i) = getframe(gca);
end
%Spins about x axis.
for i = 1:36
axis off;
rotate(oh,[1 0 0],10);
M(i) = getframe(gca);
end

To save the movie as an ‘.avi’ for future use, you can modify the above code section slightly. You create a writer object and write the video to it frame by frame (using writeVideo) as part of each forloop.

%Create writerObj
writerObj = VideoWriter('sphere.avi');  
open(writerObj)
%Animated movie of the rotation of the 3D globe
oh=findobj(gca,'type','surface');
%Spins about z axis.
for i = 1:36
axis off;
rotate(oh,[0 0 1],10);
M(i) = getframe(gca);
frame = getframe;
writeVideo(writerObj,frame);
end
%Spins about y axis.
for i = 1:36
axis off;
rotate(oh,[0 1 0],10);
M(i) = getframe(gca);
frame = getframe;
writeVideo(writerObj,frame);
end
%Spins about x axis.
for i = 1:36
axis off;
rotate(oh,[1 0 0],10);
M(i) = getframe(gca);
frame = getframe;
writeVideo(writerObj,frame);
end
close(writerObj);

Putting it all together:

format compact
set(gcf,'Menubar','none','Name','Spheres', ...
 'NumberTitle','off','Position',[10,350,400,300], ...
 'Color',[0 0 0]);
h = axes('Position',[0 0 1 1]);
%Draws sphere
[X Y Z]=sphere(20);
C = Z^2 + Y^2;
hs = surf(X, Y, Z, C);
%sets wireframe to visible
set(hs,'EdgeColor',[0.5 0.5 0.5]);
%Alters transparency of sphere
alpha('color');
alphamap('rampdown');
%Sets lighting of sphere
camlight right;
lighting phong
hidden off
axis equal
%Create writerObj
writerObj = VideoWriter('sphere.avi');  
open(writerObj)
%Animated movie of the rotation of the 3D globe
oh=findobj(gca,'type','surface');
%Spins about z axis.
for i = 1:36
axis off;
rotate(oh,[0 0 1],10);
M(i) = getframe(gca);
frame = getframe;
writeVideo(writerObj,frame);
end
%Spins about y axis.
for i = 1:36
axis off;
rotate(oh,[0 1 0],10);
M(i) = getframe(gca);
frame = getframe;
writeVideo(writerObj,frame);
end
%Spins about x axis.
for i = 1:36
axis off;
rotate(oh,[1 0 0],10);
M(i) = getframe(gca);
frame = getframe;
writeVideo(writerObj,frame);
end
close(writerObj);

Matlab: 2 Methods of Generating a Rainbow

In my data visualization class, we had an assignment to create a “rainbow” (create and display 128 vertical stripes of color in one image, in RGB sequence). Something like this:

In Matlab, a colormap is an m-by-3 matrix of real numbers between 0.0 and 1.0. Each row is an RGB vector that defines one color. The [R,G,B] color attribute value for a dataset with attribute value ranging between 0 and 1.

My original solution is:

image(1:128);
colormap(jet(128))
print -dpng 'rainbow.png'

The command colormap(jet(128)) creates a rainbow colormap with 128 colors. Files in the color folder generate a number of colormaps, and each file (in this case, “jet”) accepts the colormap size as an argument.
While this solution is certainly concise and clear, it is not the solution the professor is looking for.
It turns out that the professor wants the map to be generated algorithmically (instead of using a built-in file from the color folder).

My second solution is:

image(1:128);
R(128,1) = 0;
G(128,1) = 0;
B(128,1) = 0;
dx = 0.8;
for f=0:(1/128):1
    g = (6-2*dx)*f+dx;
    index = int16(f*128 + 1);
    R(index,1) = max(0,(3-abs(g-4)-abs(g-5))/2);
    G(index,1) = max(0,(4-abs(g-2)-abs(g-4))/2); 
    B(index,1) = max(0,(3-abs(g-1)-abs(g-2))/2);
end
%concatenate arrays horizontally
map = horzcat(R, G, B);
%map colors onto image
colormap(map)
print -dpng 'rainbow.png' 

This creates a different rainbow and satisfies the professor’s algorithmic requirement.

CodingBat Java (Assorted Warmup-1) Solutions

For warmups, CodingBat provides solutions. Some of my solutions differ from the provided.

The parameter weekday is true if it is a weekday, and the parameter vacation is true if we are on vacation. We sleep in if it is not a weekday or we’re on vacation. Return true if we sleep in.

public boolean sleepIn(boolean weekday, boolean vacation) {
    return (!weekday || vacation);
}

We have two monkeys, a and b, and the parameters aSmile and bSmile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return true if we are in trouble. 

public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
    return ((aSmile && bSmile) || (!aSmile && !bSmile)); }

Given two int values, return their sum. Unless the two values are the same, then return double their sum.

public int sumDouble(int a, int b) {
    if(a == b) {
        return 2*(a+b);
    }
    return a+b;
}

Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.

public int diff21(int n) {
    if (n <= 21) {
        return 21-n;
    }
    else {
        return (n-21)*2;
    }
}

We have a loud talking parrot. The “hour” parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return true if we are in trouble.

public boolean parrotTrouble(boolean talking, int hour) {
    return (talking && (hour < 7 || hour > 20));
}

Given 2 ints, a and b, return true if one if them is 10 or if their sum is 10.

public boolean makes10(int a, int b) {
    return (a == 10 || b == 10 || a + b == 10);
}

Given an int n, return true if it is within 10 of 100 or 200. Note: Math.abs(num) computes the absolute value of a number.

public boolean nearHundred(int n) {
    return (Math.abs(100 - n) <= 10 || Math.abs(200 - n) <= 10);
}

Given 2 int values, return true if one is negative and one is positive. Except if the parameter “negative” is true, then return true only if both are negative.

public boolean posNeg(int a, int b, boolean negative) {
    if (!negative) {
        return ((a < 0 && b > 0) || (a > 0 && b <0));
    }
    return (a<0 && b<0);
}

Given a string, return a new string where “not ” has been added to the front. However, if the string already begins with “not”, return the string unchanged. Note: use .equals() to compare 2 strings.

public String notString(String str) {
    if (str.length() >= 3 && str.substring(0,3).equals(“not”)) {
        return str;
    }
    return “not “+str;
}

Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..str.length()-1 inclusive).

public String missingChar(String str, int n) {
    return (str.substring(0,n)+str.substring(n+1,str.length()));
}

Given a string, return a new string where the first and last chars have been exchanged.

public String frontBack(String str) {
    if (str.length()>=2) {
        return (str.substring(str.length()-1,str.length())+str.substring(1,str.length()-1)+str.substring(0,1));
    }
    return str;
}

or

public String frontBack(String str) {
    if (str.length()>=2) {
        return (str.charAt(str.length()-1)+str.substring(1,str.length()-1)+str.charAt(0));
    }
    return str;
}

Given 2 int values, return true if they are both in the range 30..40 inclusive, or they are both in the range 40..50 inclusive.

public boolean in3050(int a, int b) {
    return ((30 <= a && a <= 40) && (30 <= b && b <= 40)) || ((40 <= a && a <= 50) && (40 <= b && b <= 50));
}

Given a non-empty string and an int N, return the string made starting with char 0, and then every Nth char of the string. So if N is 3, use char 0, 3, 6, … and so on. N is 1 or more.

public String everyNth(String str, int n) {
    String x = “”;
    for(int i =0; i<str.length(); i=i+n) {
        x = x+str.charAt(i);
    }
    return x;
}

Given a string, return a new string where the last 3 chars are now in upper case. If the string has less than 3 chars, uppercase whatever is there. Note that str.toUpperCase() returns the uppercase version of a string.

public String endUp(String str) {
    if (str.length()<=3) {
        return str.toUpperCase();
    }
    return (str.substring(0, str.length()-3) + (str.substring(str.length()-3, str.length())).toUpperCase());
}

CodingBat Java Solutions (Assorted)

I’m brushing up on my Java lately using a wonderful code practice site called CodingBat. Below are a few of the solutions I’ve found to their practice problems.

Given a string, return a string where for every char in the original, there are two chars.

public String doubleChar(String str) {
    String doub = “”;
    for(int i = 0; i<str.length(); i++) {
        doub = doub + str.charAt(i) + str.charAt(i);
    }
    return doub;
}

Return an array that contains exactly the same numbers as the given array, but rearranged so that every 3 is immediately followed by a 4. Do not move the 3′s, but every other number may move. The array contains the same number of 3′s and 4′s, every 3 has a number after it that is not a 3 or 4, and a 3 appears in the array before any 4. 

public int[] fix34(int[] nums) {
    int counter =0;
    for(int i =0; i<nums.length; i++) {
        if (nums[i] == 3) {
            for(int j =counter; j<nums.length; j++) {
                if (nums[j] == 4) {
                    int t = nums[i+1];
                    nums[i+1] = nums[j];
                    nums[j] = t;
                    counter = j;
                }
            }
        }
    }
    return nums;
}

Given n>=0, create an array with the pattern {1,    1, 2,    1, 2, 3,   … 1, 2, 3 .. n} (spaces added to show the grouping). Note that the length of the array will be 1 + 2 + 3 … + n, which is known to sum to exactly n*(n + 1)/2.

public int[] seriesUp(int n) {
    int[] array = new int[n];
    int[] array1 = new int[n*(n+1)/2];
    for (int i = 0; i<n;i++) {
        array[i] = i+1;
    }
    for (int j = 0; j <n; j++) {
        array1[j*(j+1)/2+j] = array[j];
        for (int x = 0; x < j+1; x++) {
            array1[j*(j+1)/2+j-x] = array[j-x];
        }
    }
    return array1;
}

Perl is a Beautiful Thing (Replace All Instances of a String in a Directory)

Perl’s string handling is a beautiful thing. I’ll talk about grep in a later post.

Let’s say you have a directory on your computer which is filled with over 1000 text/source-code documents. You want to replace all instances of a variable name, “find_var” with “replace_var”, in all files within this directory. There are a couple ways you can do this.

0. You could open each document and Ctrl+F to find each instance of the “find_var” (within the document) and manually replace it with “replace_var” Gross, several hours of tedious work.

1. You could open each document and Ctrl+H to replace all instances of “find_var” (within the document) with “replace_var” Better, but still gross & hours of work.

2. Use Perl, which replaces all instances of “find_var” (within the entire directory -subdirectories included) with “replace var” in one line. Pythonic! Or, I suppose, Perltastic/Perly…. seconds of work.

In this example, assuming the desired directory’s path is “Dropbox/desireddirectory”, you open the terminal and have two options.

Case1: If you wish to simply replace all instances of “find_var” with “replace_var”, use the following command:

perl -e “s/find_var/replace_var/g;” -pi $(find ~/Dropbox/desireddirectory -type f)

Case2: If you wish to keep a copy of the original files, use the following command:

perl -e “s/find_var/replace_var/g;” -pi.save $(find ~/Dropbox/desireddirectory -type f)

This will save back-ups of the originals of each file, attaching “.save” to their titles. Thus, doc.txt will have “replace_var”, and doc.txt.save will be a back-up of of the original “find_var”.

Pythonic Method Calling

I have an aversion to hard-coding. Hard coding is when you write out a long, elaborate code that could also be written with a dynamic loop. This usually limits the ability to easily adjust your own code in case you want to change something later (or re-use it). “Hard coding” refers to “rigidly” writing out things instead of keeping them dynamic.

This practice is frowned upon by most of the programmers I’ve met (especially the Python programmers). In Python, code is ‘pythonic’ if it is well-written and concise. This link is to an excellent article on ‘What is Pythonic?’, I highly recommend reading this for a more in-depth explanation of the term: http://blog.startifact.com/posts/older/what-is-pythonic.html

Today, while I was revising my Prime Number Algorithm program (an earlier post), I figured out how to pass functions as strings. The eval function allows me to run python code within itself. This definition of eval is vague and unhelpful.

Let me show you to make a calling method, ‘execute,’ pythonic in order to explain the purpose of the eval function.

Let’s assume that we want a program that executes methods p1(n), p2(n), …, p5(n) given some string n. I will refer to these methods collectively as ‘p’-methods.

We could hard-code this as such:

class Test():
    def execute(self, n):
        self.p1(n)
        self.p2(n)
        self.p3(n)
        self.p4(n)
        self.p5(n)

    def p1(self,n):
        print “Hello”+n
    def p2(self,n):
        print “Hello2″+n
    def p3(self, n):
        print “Hello3″+n
    def p4(self,n):
        print “Hello4″+n
    def p5(self,n):
        print “Hello5″+n

if __name__ == ‘__main__’:
    test = Test()
    test.execute(‘ World!’)

The above program will run all 5 ‘p’-methods and print the appropriate strings. However, what if there were 1000 different ‘p’-methods we needed to run? Must we type out each method in order to call these ‘p’-methods within the execute method?

At first, I created a forloop to iteratively call execute, providing a new method each time. If you run the code below, execute will treat the ‘method’ parameter as a String type (instead of a function) and throws an error.

(NON-FUNCTIONAL)

class Test():
    def execute(self, method_name):
        self.method_name(‘ World!’)   

    def send_method(self):
        for version in xrange(1,6):
            version = str(version) #run each ‘p’-method version = 1, 2, 3, 4
            method = ‘self.’+’p’+version #note that type(method == String
            self.execute(method)

    def p1(self,n):
        print “Hello”+n
    def p2(self,n):
        print “Hello2″+n
    def p3(self, n):
        print “Hello3″+n
    def p4(self,n):
        print “Hello4″+n
    def p5(self,n):
        print “Hello5″+n

if __name__ == ‘__main__’:
    test = Test()
    test.send_method()

We are so very close to having a pythonic solution. In order to fix this error, we must make the String into a method call. With one extra line, we evaluate the String input (‘method_name’) as a function and run all ‘p’-methods! The final version of the execute method is:

class Test():
    def execute(self, method_name):
        method = eval(method_name)
        methodrun = method(‘ World!’)   

    def send_method(self):
        for version in xrange(1,5):
            version = str(version) #test each version of the algorithm, version = 1, 2, 3, 4
            method = ‘self.’+’p’+version
            self.execute(method)

    def p1(self,n):
        print “Hello”+n
    def p2(self,n):
        print “Hello2″+n
    def p3(self, n):
        print “Hello3″+n
    def p4(self,n):
        print “Hello4″+n
    def p5(self,n):
        print “Hello5″+n

if __name__ == ‘__main__’:
    test = Test()
    test.send_method()

I hope this gives you an idea of: why hard-coding is bad, what ‘pythonic’ means, how ‘eval’ comes in handy and what I do in my free time.

Listing Programming Languages on Your Resume

I love programming and know a few programming languages. Every programmer I’ve met has a favorite language, however, most of us can code in more than one language. As I was revising the ‘Language’ portion of my resume, I became confused.

Should you mention all the languages you can code in?

What if they expect you to be practiced in (insert language you haven’t used in the last 3 months) and you fail the interview?

Should you be safe and only list the languages you are fluent in?

How do you simply represent skill level in languages?

I decided to divide my knowledge of languages into “proficient” and “familiar.” Here is a guide on how to sort your languages into these two categories.

If you are “proficient” at a programming language, you can sit down and code (without consulting the internet or a book) and produce a functional program. You can write efficient, concise code in this language. If given source code, you can optimize it.

If you are “familiar” at a programming language, you’ve coded at least 5 functional programs in this. You can code a simple program with no bugs. If given internet access, you can produce a complex program. If given source code in this language, you can understand what it does and check for errors. You will likely think “I know how to do this in (insert proficient language here)! How do I do this in (insert familiar language here)?” over 3 times while coding a simple program.

For example, my ‘Language’ section currently looks like this:

(I added my knowledge of Braille and Morse Code because it amuses me to present all types of languages in my language section.)

Implementation of Prime Number Algorithms

I’m currently reading Algorithms Unplugged, lent to me by my friend and professor, Dr. Marr.

The text provided 4 versions of an algorithm and claimed that each new version had a noticeable increase in runtime efficiency.

These algorithms take some number n and return a list of all prime numbers up to and including n. For example, if n = 13, this algorithm returns [2,3,5,7,11,13].

I was skeptical of their claims \(\Rightarrow\) I took the pseudocode and converted it into functional Python, then wrote a timing function: this tests each algorithm by letting n = 2^6 to 2^20 and repeating each calculation 1000 times (in order to find the average runtime).

I had to wrestle with Python in order to stop it from rounding off the calculated runtimes (treating runtime as a float), which lead to an interesting adventure into the time module man page.

tl;dr

  • take pseudocode from a book (p.121-127 of Algorithms Unplugged by various German computer scientists*)
  • translate said pseudocode into functional code, and
  • test the run-times of each algorithm

'''
Catherine Ray
prime_runtime0.py
'Algorithms Unplugged' Demonstration
Program uses algorithms listed in pseudocode from pg.119-127. Each algorithm returns a list of all primes up to some number n.
There are 4 versions of this algorithm; this program computes the average runtimes of each version and prints to stdout.
'''
import math
import time as t
class Runtime():
 def execute(self):
  repeat = 1000 #number of times to repeat runtime calculation
  n = [2**x for x in xrange(6, 21, 7)] #produce list of large numbers to test algorithms
  #n = [2**6, 2**20]
  for v in xrange(1,5):
   method = 'self.prime_number'+str(v) #test each version of the algorithm, version = 1, 2, 3, 4
   print 'ntVersion ' + str(v), 'nHighest Prime Number Computed : Average Runtimen'  #find runtime
   [self.runtime(method, number, repeat) for number in n] 
 def runtime(self, method, n, repeat):
 #function = function to test
 #n = highest prime to compute
 #repeat = number of trials to run
  method = eval(method)
  total = 0 #reset total
  for r in xrange(0, repeat+1): 
   start = t.time() #get start time
   methodrun=method(n) 
   end = t.time() #get end time
  total = total + end-start #add to previously calculated time
  average_time = total/repeat #find average runtime
  print  '2^%d :' %(int(math.log(n)/math.log(2))), average_time
 def prime_number1(self, n): #version 1, pg. 121
  list = [i for i in xrange(2,n+1)] #write down all numbers between 2 and n in a list
  for i in xrange(2, n+1):
   for k in xrange(2, n+1):
    if i*k in list: list.remove(i*k) #if i*k is in list, remove
    else: pass #if i*k isn't in list, do nothing
  return list
 def prime_number2(self, n): #version 2, pg. 123
  list = [i for i in xrange(2,n+1)] #write down all numbers between 2 and n in a list
  for i in xrange(2, int(math.floor(math.sqrt(n)))+1):
   for k in xrange(2, int(math.floor(n/i))+1):
    if i*k in list: list.remove(i*k) #if i*k is in list, remove
    else: pass #if i*k isn't in list, do nothing
  return list
 def prime_number3(self, n): #version 3, pg. 125
  list = [i for i in xrange(2,n+1)] #write down all numbers  between 2 and n in a list
  for i in xrange(2, int(math.floor(math.sqrt(n)))+1):
   if i in list:
    for k in xrange(2, int(math.floor(n/i))+1):
     if i*k in list: list.remove(i*k) #if i*k is in list, remove
     else: pass #if i*k isn't in list, do nothing
  return list
 def prime_number4(self, n): #final version, pg.127
  list = [i for i in xrange(2,n+1)] #write down all numbers between 2 and n in a list
  for i in xrange(2, int(math.floor(math.sqrt(n)))+1):
   if i in list:
    for k in xrange(int(math.floor(n/i)), i-1, -1):
     if k in list:
      if i*k in list: list.remove(i*k)  #if i*k is in list, remove
      else: pass #if i*k isn't in list, do nothing
  return list
if __name__ == '__main__':
 runtime = Runtime()
 runtime.execute()

I left the code to run overnight.

Taking a brief glance at the output, I found confirmation of the authors’ claims. The runtime each version is less than the previous version (version4 should take less time to run than version1).


*Berthold Vöcking, Helmut Alt, Martin Dietzfelbinger, Rüdiger Reischuk, Christian Scheideler, Heribert Vollmer, Dorothea Wagner