当前位置:首页 » 《随便一记》 » 正文

Python和Matlab对照表

14 人参与  2022年12月21日 12:03  分类 : 《随便一记》  评论

点击全文阅读


Matlab vs. Python

Create

OperationMatlabPython
1d array: size (n, )Not possibleA = 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 kA = j:k:nA = np.arange(j, n+1, k)
Create a matrixA = [1 2; 3 4]A = np.array([[1, 2], [3, 4]])
Uniform random numbersA = rand(2, 2)A = np.random.rand(2, 2)
random intrandperm(5)shuffle(range(5));
np.random.permutation(5)

Manipulating Vectors and Matrices

OperationMatlabPython
TransposeA.’A.T
Complex conjugate transpose (Adjoint)A’A.conj()
ReshapeA = reshape(1:10, 5, 2)A = A.reshape(5, 2)
Convert matrix to vectorA( : )A = A.flatten()
Repeat matrixrepmat(A, 3, 4)np.tile(A, (4, 3))
Preallocating/Similarx = 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 stringA=[‘str1’,‘str2’];A=‘str1’+‘str2’
SplitB=split(A,‘-’)B=A.split(‘-’)
concatenateC=[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 axispermute(A,[2,1,3])transpose(A,[2,1,3])
Seed settingrng(5)np.random.seed(5)

Accessing Vector/Matrix

OperationMatlabPython
Get dimensions of matrix[nrow ncol] = size(A)nrow, ncol = np.shape(A)
Step slicingA(1:2:6)A[1:7:2]
Shape/Sizesize(A,1)np.size(A,0), A.size # 不加维度是所有元素个数
np.shape(A)[0], A.shape[0] # shape返回的是一个tuple
SelectA(A>0)=[];A[A>0]=[];
indexA(2)A[2]

Mathematical Operations

OperationMatlabPython
Matrix multiplicationA * BA @ B
Element-wise multiplicationA .* BA * B
Matrix to a powerA.^2A**2
Inverseinv(A) A^(-1)np.linalg.inv(A)
min of each columnmin(A, [], 1)np.amin(A, 0)
min of entire matrixmin(A( : ))np.amin(A)
argmaxvec2ind(A)argmax(A,axis=0)
Memebrismember(A,B)np.isin(A,B)
Counttabulate(A)from collections import Counter
Counter(A)

Programming

OperationMatlabPython
Comment block%{ Comment block %}# Block # comment # following PEP8
Function: anonymousf = @(x) x^2f = lambda x: x**2
logical expressionif a == 1 or b == 3:if a == 1
Output omitting~__

System

OperationMatlabPython
Clear console commandclcclear
Clear varclear name1, name2del name1, name2
clear allclearreset

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]])

点击全文阅读


本文链接:http://zhangshiyu.com/post/50102.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1