Compact python primer for MATLAB users #
The code below is a quick reference on how to do things in python using numpy and matplotlib that you probably do regularly if you are a MATLAB user.
It serves as a super compact MATLAB to Python cheatsheet.
Common Operations: sinusoids, ffts, and plotting #
# matlab-esque things in python
# first always import numpy and matplotlib
import matplotlib.pyplot as plt
import numpy as np
# basic signal creation
# matlab, x = exp(1i*2*pi*(0:Nsamples)*f/fs);
fs = 5000
f = 500
Nsamples = 50
x = np.exp(1j * 2 * np.pi * np.arange(Nsamples) * f / fs)
# basic plotting, much like matlab
plt.figure(1)
plt.subplot(2,1,1)
plt.plot(np.arange(Nsamples), np.real(x), marker='o', linestyle='dashed')
plt.title('real portion of signal x')
plt.grid()
plt.xlabel('sample')
plt.ylabel('magnitude')
plt.legend('real')
plt.subplot(2,1,2)
plt.plot(np.arange(Nsamples), np.imag(x), marker='x', linestyle='dashed')
plt.title('imag portion of signal x')
plt.xlabel('sample')
plt.ylabel('magnitude')
plt.legend('imag')
plt.grid()
plt.draw()
# 2nd figure
plt.figure(2)
plt.plot(np.real(x), np.imag(x), marker='x')
plt.title('complex samples')
plt.draw()
# fft example + figure
x_fft = np.fft.fftshift(20*np.log10(np.abs(np.fft.fft(x, Nsamples))))
# equivalent to [-.5:1/Nsamples:.5-1/Nsamples] in matlab
xaxis = np.arange(-0.5, 0.5, 1/Nsamples)
plt.figure(3)
plt.plot(xaxis, x_fft, marker='o', linestyle='dashed')
plt.title('real portion of signal x')
plt.grid()
plt.xlabel('sample')
plt.ylabel('magnitude')
plt.legend('real')
# put last to show all figures
plt.show()
Common Function Conversions #
MATLAB | Python |
---|---|
size(A) | A.shape |
length(A) | len(A) |
zeros(m, n) | numpy.zeros((m, n)) |
ones(m, n) | numpy.ones((m, n)) |
eye(n) | numpy.eye(n) |
rand(m, n) | numpy.random.rand(m, n) |
randn(m, n) | numpy.random.randn(m, n) |
linspace(a, b, n) | numpy.linspace(a, b, n) |
logspace(a, b, n) | numpy.logspace(a, b, n) |
reshape(A, m, n) | numpy.reshape(A, (m, n)) |
transpose(A) | numpy.transpose(A) or A.T |
cat(dim, A, B) | numpy.concatenate((A, B), axis=dim) |
mean(A) | numpy.mean(A) |
sum(A) | numpy.sum(A) |
min(A) | numpy.min(A) |
max(A) | numpy.max(A) |
std(A) | numpy.std(A) |
var(A) | numpy.var(A) |
abs(A) | numpy.abs(A) |
sqrt(A) | numpy.sqrt(A) |
exp(A) | numpy.exp(A) |
log(A) | numpy.log(A) |
log10(A) | numpy.log10(A) |
sin(A) | numpy.sin(A) |
cos(A) | numpy.cos(A) |
tan(A) | numpy.tan(A) |
asin(A) | numpy.arcsin(A) |
acos(A) | numpy.arccos(A) |
atan(A) | numpy.arctan(A) |
ceil(A) | numpy.ceil(A) |
floor(A) | numpy.floor(A) |
round(A) | numpy.round(A) |
mod(A, B) | numpy.mod(A, B) or A % B |
power(A, B) | numpy.power(A, B) or A ** B |
max(A, B) | numpy.maximum(A, B) |
min(A, B) | numpy.minimum(A, B) |
unique(A) | numpy.unique(A) |
find(A) | numpy.where(A) |
isempty(A) | len(A) == 0 |