Matlab vs. Python
Create
Operation | Matlab | Python |
---|---|---|
1d array: size (n, ) | Not possible | A = np.array([1, 2, 3]) |
Row vector: size (1, n) | A = [1 2 3] | A = np.array([1, 2, 3]).reshape(1, 3) |
Column vector: size (n, 1) | A = [1; 2; 3] | A = np.array([1, 2, 3]).reshape(3, 1) |
Integers from j to n with step size k | A = j:k:n | A = np.arange(j, n+1, k) |
Create a matrix | A = [1 2; 3 4] | A = np.array([[1, 2], [3, 4]]) |
Uniform random numbers | A = rand(2, 2) | A = np.random.rand(2, 2) |
random int | randperm(5) | shuffle(range(5)); np.random.permutation(5) |
Manipulating Vectors and Matrices
Operation | Matlab | Python |
---|---|---|
Transpose | A.’ | A.T |
Complex conjugate transpose (Adjoint) | A’ | A.conj() |
Reshape | A = reshape(1:10, 5, 2) | A = A.reshape(5, 2) |
Convert matrix to vector | A( : ) | A = A.flatten() |
Repeat matrix | repmat(A, 3, 4) | np.tile(A, (4, 3)) |
Preallocating/Similar | x = rand(10); y = zeros(size(x, 1), size(x, 2)) | x = np.random.rand(3, 3); y = np.empty_like(x) # new dimsy = np.empty((2, 3)) |
Cat string | A=[‘str1’,‘str2’]; | A=‘str1’+‘str2’ |
Split | B=split(A,‘-’) | B=A.split(‘-’) |
concatenate | C=[A,B]; C=cat(2,A,B); C=[A;B] | C=np.append(A,B,axis=1) # 只可以拼接两个; C=np.concatenate((A,B),aixs=1) # 可以拼接多个; C=np.hstack((A,B)) (适用于三个以上, 横向拼接); C=np.vstack((A,B)) (竖向拼接); |
swap axis | permute(A,[2,1,3]) | transpose(A,[2,1,3]) |
Seed setting | rng(5) | np.random.seed(5) |
Accessing Vector/Matrix
Operation | Matlab | Python |
---|---|---|
Get dimensions of matrix | [nrow ncol] = size(A) | nrow, ncol = np.shape(A) |
Step slicing | A(1:2:6) | A[1:7:2] |
Shape/Size | size(A,1) | np.size(A,0), A.size # 不加维度是所有元素个数 np.shape(A)[0], A.shape[0] # shape返回的是一个tuple |
Select | A(A>0)=[]; | A[A>0]=[]; |
index | A(2) | A[2] |
Mathematical Operations
Operation | Matlab | Python |
---|---|---|
Matrix multiplication | A * B | A @ B |
Element-wise multiplication | A .* B | A * B |
Matrix to a power | A.^2 | A**2 |
Inverse | inv(A) A^(-1) | np.linalg.inv(A) |
min of each column | min(A, [], 1) | np.amin(A, 0) |
min of entire matrix | min(A( : )) | np.amin(A) |
argmax | vec2ind(A) | argmax(A,axis=0) |
Memebr | ismember(A,B) | np.isin(A,B) |
Count | tabulate(A) | from collections import Counter Counter(A) |
Programming
Operation | Matlab | Python |
---|---|---|
Comment block | %{ Comment block %} | # Block # comment # following PEP8 |
Function: anonymous | f = @(x) x^2 | f = lambda x: x**2 |
logical expression | if a == 1 or b == 3: | if a == 1 |
Output omitting | ~ | __ |
System
Operation | Matlab | Python |
---|---|---|
Clear console command | clc | clear |
Clear var | clear name1, name2 | del name1, name2 |
clear all | clear | reset |
Matlab与python的计数方向不同
matlab是按竖向计算, python是横向>> A=[1,2,3;4,5,6;7,8,9]A = 1 2 3 4 5 6 7 8 9>> reshape(A,[1,9])ans = 1 4 7 2 5 8 3 6 9
In [91]: A=np.array([[1,2,3],[4,5,6],[7,8,9]]) #注意matlab初始化的不同In [92]: np.reshape(A,[1,9])Out[92]: array([[1, 2, 3, 4, 5, 6, 7, 8, 9]])