# Matlab to Python – some code examples

Two years back, I was converting a matlab script to python, here are some of the errors that I encountered during the conversion. Found them documented in that converted script, posting them here for wider audience.

```

```

Matlab to Python

1. () to []

```nd=topo(j,i)
X(j,i)=coords(nd,1)
Y(j,i)=coords(nd,2)
```

SyntaxError: can't assign to function call

```nd=topo[j,i]
X[j,i]=coords[nd,1]
Y[j,i]=coords[nd,2]
```

2. 1 to 0

```X(j,i)=coords(nd,1)
Y(j,i)=coords(nd,2)
```

IndexError: index (2) out of range (0<=index<2) in dimension 1

```X[j,i]=coords[nd,0]
Y[j,i]=coords[nd,1]
```

3. zeros to zeros

B=zeros(2,edof)

In Python

```B=np.zeros((2,edof))
```

4. array to array

D=G*[1 0; 0 1];

in python

```D_ps=G* np.array([[1.0,0.0],[0.0,1.0]])
```

5. % to #

Python

```# is comments in python
```

6. For to for

for i=1:nnel
node(i)=nodes(iel,i);
end

python

```for i in range(nnel):
node[i]=nodes[iel,i]
```

7. Matlab find to python find

L1 = find(coordinates(:,2)==min(coordinates(:,2)))

in python

```l1 = np.where(coords[:,1]==np.min(coords[:,1])
```

# Coming to Numpy from Matlab – bookmark this I am old time matlab user. After C and fortran discovered matlab while working in NAL.

Once hooked, have not touched excel for any computation, at least in NAL. But after NAL, the trend declined, mostly due to unavailability of matlab.

But now when I am write python(which I do a lot 🙂 ), I keep using matlab commands/syntax in python, so this is one link that I often visit when I am stuck with a python equivalent of matlab function..

Numpy for Matlab users

Good webpage to bookmark if you are coming to numpy from matlab.

Converted the page to pdf for easy download, for those like me, who do not want to open the browser in the middle of coding sprint!!

Thanks Mathesaurus

Do you any such good resource?

# Few examples of Matlab to Python conversions A few days back, was converting a matlab code to python. Out of habit , I kept going back to matlab syntax. I logged all places that I made these errors.

So here are the notes. Hope its of some use.

1. () to []

```nd=topo(j,i)
X(j,i)=coords(nd,1)
Y(j,i)=coords(nd,2)
```

SyntaxError: can’t assign to function call

```nd=topo[j,i]
X[j,i]=coords[nd,1]
Y[j,i]=coords[nd,2]
```

2. 1 to 0

```X(j,i)=coords(nd,1)
Y(j,i)=coords(nd,2)
```

IndexError: index (2) out of range (0<=index<2) in dimension 1

```X[j,i]=coords[nd,0]
Y[j,i]=coords[nd,1]
```

3. zeros to zeros

```B=zeros(2,edof)
```

the correct form

```B=np.zeros((2,edof))
```

4. array to array

```D=G*[1 0; 0 1];
```

in python

```D_ps=G* np.array([[1.0,0.0],[0.0,1.0]])
```

5. % to #

```% is comments in matlab
```
```# is comments inpython
```

6. For to for

```for i=1:nnel
node(i)=nodes(iel,i);
end
```

python

```for i in range(nnel):
node[i]=nodes[iel,i]
```

7. Matlab find to python find

```L1 = find(coordinates(:,2)==min(coordinates(:,2)))
```

in python

```l1 = np.where(coords[:,1]==np.min(coords[:,1])

```

# Gotchas in Python For Matlab Users “What an odd place to put these comments!” This was my first thought when I saw this. With goal of Apprentice to Guru in mind, I was browsing through some python code and came upon this python file by Roland Memisevic.

Lot of useful information for anyone moving to python from matlab.

# Common Pitfalls to Avoid while converting Matlab code to Python After fortran and excel, my most used piece of software/language/tool was Matlab. It has been a constant companion in office for me for quick prototyping. Seriously started using it when I was in NAL and ever since have used it off and on in office.

Then came python and slowly python has become my numerical/computation engine of choice, apart from the various benefits of using python, I love the fact that unlike matlab, for comparison, there isn’t any limit in python. All kind of tasks and computations can be done with minimum effort. Be it numerical computation or website management.

And thanks to the Python packages NumPy, SciPy , Sympy and Matplotlib, most MATLAB code can be almost cleanly and easily translated to Python code. There are however some clear differences that must be accounted for.

Zero index – Python uses a zero-indexing standard, while MATLAB uses a one-indexing standard, making most algorithms give a one-off error if directly converted. This is quickly fixed, but requires some application of thought for algorithms where the index is part of the mathematical calculations. If you are converting Matlab to python, this is the most slippery zone.

Differencing between arrays and functions – or difference between () and [] – Python does not allow accessing arrays by the a(1) standard and instead uses a. This can cause some confusion as to why a function will not run but can be quickly eliminated, as it casts an error. Functions are still called with soft parentheses. If your are converting Matlab to Python, this is the most frequent mistake you will do.

Slicing arrays – A Python slice of an array is issued with the : operator like MATLAB, but unlike MATLAB, beginning and end are assumed unless stated otherwise. Unlike MATLAB, slice operations in python do not copy the array, but simply provides a view into it. This can cause problems with iterative algorithm that assumes the array is constant – Python uses the copy function to copy arrays, where MATLAB copies them as default. This is a mistake that’s hard to debug during compilation, so be extra careful.

And the biggest pitfall of all is the integer division.

Maybe since Python was not exclusively designed as a numeric language, it does not automatically cast integer division as a floating point number, should the division not have an integer solution. Python automatically casts integer division to another integer, rounding the result down. This can prove problematic if any of the mathematical expressions include a fraction like 3/2

It can be easily corrected with two easy solutions.

1. Adding a punctuation mark after the integer, to indicate it should be treated as a floating point value. In the above example we would then write 3./2. instead of 3/2

2. Importing the built-in function to convert integer division to floating point numbers automatically. This will require the very first line of code in the relevant file to be “from __future__ import division”

image credit:hawaiivaloans.com

Do you know of any other pitfalls?

# Top 5 posts

These posts have been the most popular for the first half of 2013!

Ever green post. Always stays at the top. Lot of people converting fortran into DLL’s!

3 steps is all that is needed to get a gif animation from matlab!

An GIF animation to explain the Gas turbine blade nomenclature! Will never forget this again!

Gfortran and Excel. This explains how to create fortran DLL in gfortran and call it with excel using a simple example.

Random numbers are everywhere. And this module in fortran to generate non-uniform random numbers is quite popular!

# GIF animation in Matlab in 3 steps Videos are cool. But if you need an animation to put in documentation or a PowerPoint then GIF is the way to go.

So building on the previous post of getting a video of your simulation from matlab, this post explains three simple steps to get a GIF animation from mat lab.

The steps are simple.

1. Define the data structure to hold the image data.
2. Plot and get the frame
3. Store the frame image in the data structure
4. Create the GIF animation.

As always lets begin with a data to plot.

`x=rand(100,10);`

Won’t explain much about the data structures and command as Matlab documentation does a good job at that.

I will explain the how to of doing it without much effort. Leave a comment if you are stuck, will try to resolve it.

1. Define the data structure or for shortcut let Matlab provide it.

```plot(x(:,k))
figure,
f = getframe;
[im,map] = rgb2ind(f.cdata,256,'nodither');
```

2. Store and get the frame image in the data Structure.

im is the data structure.

```for k=1:10,
plot(x(:,k);
f=getframe;
im(:,:,1,k) = rgb2ind(f.cdata,map,'nodither');
end

```

rgb2ind gets the pixel data to the im data structure.

3. Write out the image file.

```imwrite(im,map,'imagefile.gif','DelayTime',0,'LoopCount',inf);

```

check Matlab help for other options.

Well that’s it. 3 steps for a gif animation from matlab

While I am with Matlab, I like this little bit of interesting history on the birth of Matlab. Shows how little bets bloom into something so big and useful.

Cleve Moler, the chairman of the computer-science department at the University of New Mexico, started developing MATLAB in the late 1970s. He designed it to give his students access to LINPACK and EISPACK without them having to learn Fortran. It soon spread to other universities and found a strong audience within the applied mathematics community. Jack Little, an engineer, was exposed to it during a visit Moler made to Stanford University in 1983. Recognizing its commercial potential, he joined with Moler and Steve Bangert. They rewrote MATLAB in C and founded MathWorks in 1984 to continue its development. These rewritten libraries were known as JACKPAC. In 2000, MATLAB was rewritten to use a newer set of libraries for matrix manipulation, LAPACK.

From wikipedia