Few examples of Matlab to Python conversions

Matlab to PythonA 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])

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s