oslo – Elektromagnetisme http://elektromagnetisme.no The home of FYS1120 Mon, 20 Oct 2014 11:23:54 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.3 28429679 Using Python in the first MAT1120 oblig http://elektromagnetisme.no/2010/09/13/using-python-in-the-first-mat1120-oblig/ http://elektromagnetisme.no/2010/09/13/using-python-in-the-first-mat1120-oblig/#respond Mon, 13 Sep 2010 13:00:04 +0000 http://mindseye.no/?p=84 Continue reading ]]> The first “oblig” (mandatory exercise) in the subject MAT1120 is now available. I am trying to do as much work as possible in Python instead of Matlab, but as always this creates some extra effort when the subject is oriented around the latter.

Already in the first exercise there is a minor challenge, since the data file is not stored as a simple array, but as Matlab code. This means we need to rewrite this file to Python code or run it in Matlab and export it as data instead. As I am currently using a computer without Matlab installed and being to lazy to connect to a server with Matlab via remote desktop, I decided to do the latter. (I might add that I also wanted to see if I could do this without Matlab at all).

First of all, I figured the data was stored in the following manner:

n=28;
B=zeros(n);

B(1,1)=0.3;
B(1,2)=0.3;
B(1,3)=0.2;

This is quite similar to Python code, but the parentheses should be square brackets and the zeros function requires NumPy. Thus, we need a way to replace these. Using regular expressions was the most probable useful way to do this. Thanks to the Gedit Regex Plugin I managed to do this without even opening a terminal. The needed Regex code was as follows:

Search for: B\((.*?)\)
Replace with: B[\1]

This will match any line with a “B” and replace the round brackets with square ones.  Notice that we don’t need any more fancy regex in this example as there are no other B’s with round brackets getting caught by our search.

The last challenge is to match the dimensions of the array. Matlab stores all n \times n matrices with indexes running from 1 \to n, while Python uses indexes from 0 \to n - 1.

First of all, we need to make the dimensions of the array n+1 to make sure the indexes used to insert the variables are not out of bounds, and in the end we need to delete the first row and column.

Luckily, this is easy to achieve by adding +1 to the zeros function:

B=zeros((n+1,n+1));

And by using the delete function from NumPy:

B=delete(B,1,1) # removes the first and row and column
B=delete(B,1,0)

You may download the finished Python version of the file here.

Note that when you are continuing to do these exercises you should convert B to a matrix whenever you need to do matrix multiplication. You might also use the B.dot(B) function, but there is no such equivalent for exponentials (powers). Check out this page for more info about differences between matrices and arrays in NumPy.

]]>
http://elektromagnetisme.no/2010/09/13/using-python-in-the-first-mat1120-oblig/feed/ 0 84