Skip to content
Snippets Groups Projects
python_vs_matlab.md 5.72 KiB

Comparison of Python and Matlab

Originally from this page but modified to 1) be in markdown, 2) fix some errors, and 3) add more detail.

This is very much a work in progress. This re-formatting is taking some time.

Python Matlab
  • numeric variables are double precision if decimal added
a = 5.  # this is a float
a = 5  # this is an int
  • numeric variables are double precision by default
a = 5.0;  % this is a double
Eve Jackson

test

numeric arrays are objects defined in NumPy package
indexes start at 0 in Python
structures are defined by indentation, no 'end'
A = np.empty(10) # initialize array A| array indexes start at 1 in Matlab
indentation is for readability only
for i=1:10
A(i) = i; for i in range(1,11): | end     A.append(i) | A % display contents of A     print(A[i-1])  | |

repeat which prints a series of |

values  | for i=0:2:10

|	    fprintf(' %i \n', i)

for i in range(0,11,2): | end     print(i) | |

initialize an identity matrix  |

|	% MATLAB has built-in functions for

import the numpy library for matrix operations | % common array initializations

|	

import numpy as np | B = eye(100); | B = np.identity(3) | |

declare and initialize an array, | C = [1, 2, 3];  % or C = [1 2 3];

known as a list in Python |

|	

C = [1, 2, 3] | |

initialize and print an array |

array name = arange(start,stop,step) | % array name = [start:increment:end];

|	

import numpy as np | C = np.arange(2,10,2) | C = [2:2:8] % leave off ; to display value print(C) | |

print an array element on screen |

array indexes start at 0   | % array indexes start at 1

|	

print(C[1])  | C(2) |

prints 4 using C from above table cell | % prints 4 using C from above table cell

note square brackets C[1] | % note parentheses C(2)

|	

declare and initialize an array |

with fixed interval between values |

import numpy as np | C = np.linspace(2,8,4) | C = linspace(2,8,4);

third param is optional and = # points |

between and including 1st two points | % third param is optional and = # points

if third param left off, default | % between and including 1st two points

is 50 points | % if third param left off, default

|	% is 100 points

initialize a 2D array | % these three examples accomplish the

|	% same thing
|	

D = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] | D = [1 2 3; 4 5 6; 7 8 9]; | D = [1:3; 4:6; 7:9]; | D = [1 2 3 |      4 5 6 |      7 8 9];

print element of 2D array  | % array indexes start at 1

array indexes start at 0  |   

print(D[1][1]) # row 2, column 2 | # prints 5 using D from above table cell | D(2,2) % row 2, column 2 | % prints 5 using D from above table cell

print selected sub array of 2D array |

# e.g., print rows 1 to 2 of column 1  | | D(1:2,1) % rows 1 to 2 of column 1 for i in range(0,2): |     print(D[i][0]) | |

print all rows of column 1 of 2D |

array |

|	

import numpy as np | D(:,1) % all rows, column 1 D = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) | Dsub = D[0:,0:1] | print(Dsub) | |

logical expression |

|	

a = 1 | a = 1 b = 2 | b = 2; if a == 1 or  b == 3: | if a == 1 || b == 3     print('a = 2 or b = 3') |     fprintf('a = 2 or b = 3 \n'); | end  | # if structure | | if a == 1 and b != 3: | if a == 1 && b ~= 3     print('a=1 and b not 3'); |     fprintf('a=1 and b not 3 \n');     print('OK?') |     fprintf('OK? \n'); | end |

if, else structure |

|	a ~= 1

if a != 1: |     fprintf('a is not 1 \n')     print('a is not 1') | elseif b ~= 3  elif b != 3: |     fprintf('b is not 3 \n')     print('b is not 3') | else else: |     fprintf('huh? \n')     print('huh?') | end |

switch structure |

|	switch menuChoice

Python doesn't have a switch structure |     case 1

|	        % can do any actions in a case, e.g.,

any switch structure can be |         % call a user-defined function

written as an if-else structure |         myMenuFunc01();

|	    case 2

switch structures may be quicker to |         myMenuFunc02();

read and write for applications such as menus |     case 3

|	        myMenuFunc03();
|	    otherwise
|	        fprintf('invalid selection, try again')
|	end
|	

program which calls a user-defined function | % main program and function definition must

|	% be in separate files and function file

define function, here I chose name myfunc | % must have same name as function name

|	

def myfunc(x,y): | z = myfunc(2,3)     return x**y # ** is exponentiation operator | % prints 8 for this input |

call function | ----- LISTING OF FILE myfunc.m ------

|	

z = myfunc(2,3) | function returnValue = myfunc(x,y) print(z) |    returnValue = x^y; % ^ is exponentiation operator

prints 8 for this input |

|	   % function is a keyword
|	   % returnValue is arbitrary variable name
|	     

matrix multiplication |   

|	  

import numpy as np |    | A = [2,3; 3,5]; A = np.matrix( ((2,3), (3, 5)) ) | B = [1,2; 5,-1]; B = np.matrix( ((1,2), (5, -1)) ) | | C = A * B C = A * B | print(C)  | |

plotting |

|	

import numpy as np | import matplotlib.pyplot as plt | x = np.linspace(0,2np.pi,100) | x = linspace(0,2pi,100); y = np.sin(x) | y = sin(x); plt.plot(x,y) | plot(x,y) plt.ylabel('sin(x)') | ylabel('sin(x)') plt.xlabel('x') | xlabel('x')  plt.show()  |