What is Matlab? It is the classic VB in the field of computing. They are at the bottom of the contempt chain in their respective fields.
Of course, this disdain chain is the disdain chain of programmers. For those who do not want to have an in-depth understanding of programming, they can ignore it, and there is no need to continue reading this article. However, considering the price of small millions, Octave, an open source computing tool with almost the same syntax as Matlab, is recommended for those who do not want or cannot leave Matlab.
Basic difference
Annotation scheme: use% in Matlab and% in Python #.
The index of Matlab starts from 1 by default and passes (); Python starts with 0. Use [].
Strings in python are represented by single or double quotation marks.
Circulation and judgment
matlab terminates a piece of code by end, while python represents the scope by indentation, and its declaration is separated from the scope by:.
Here is a comparison between for and if:
%This is octave Code, looks like CSDN I won't support it matlab Highlight... It's still used here python Highlight of x = rand(10,1); for i = 1:10 if x(i)<0.3 fprintf("%f<0.3\n",x(i)); else if x(i)>0.6 fprintf("%f>0.6\n",x(i)); else printf("%f\n",x(i)); end %matching else if Medium if end end % The following is its output 0.077700<0.3 0.203065<0.3 0.578026 0.752277>0.6 0.380363 0.541303 0.520777 0.031512<0.3 0.042714<0.3 0.986611>0.6 >>
#This is python code import numpy as np x = np.random.rand(10) for i in range(10): if x[i]< 0.3: print(x[i],"<0.3") elif x[i]>0.6: print(x[i],">0.6") else: print(x[i]) # The following is the output of python 0.13810550482646344 <0.3 0.05145857194203651 <0.3 0.40510564390649306 0.01924290850447119 <0.3 0.3126615170549344 0.9716907139903828 >0.6 0.3306312812282888 0.08156490331007271 <0.3 0.24120991717365392 <0.3 0.7177679530429059 >0.6 >>>
The same is true for while, and break and continue are basically the same.
switch
switch...case can be used in Matlab. This syntax is not available in python and can be replaced by a dictionary.
x = [1,2,3,3,2,1]; for i = 1:6 switch x(i) case 1 disp('one') case 2 disp('two') otherwise disp('three') end end % Next bit calculation results one two three three two one
In python, it can be written as follows:
dic = {1:"one",2:"two",3:"three"} #Define a dictionary for i in x: print(dic[i]) # The output results are shown below one two three three two one
function
The function identifiers of Matlab and Python are function and def respectively. Next, write a factorial
% This is octave code function y = fac(x) if x>1 y = x*fac(x-1); else y = 1; end end % The following bit calls the result >> fac(5) ans = 120
# This is python code def fac(x): return x*fac(x-1) if x > 1 else 1 #The following is the call >>> fac(5) 120
Anonymous function
% matlab >> sqr = @(x) x^2; >> sqr(3) ans = 9 >> (@(x) x^2)(5) ans = 25
>>> sqr = lambda x:x**2 >>> sqr(3) 9 >>> (lambda x:x**2)(5) 25 >>> fac = lambda x : x*fac(x-1) if x > 1 else 1 >>> fac(5) 120
cell
The cell in Matlab is equivalent to the list in Python.
# This is python code >>> x = [1,'2',3,[4,5]] >>> x [1, '2', 3, [4, 5]]
class
A class in Matlab is a file, and the file name is the same as the class name. The file needs to be in the current working path
% This is Person.m Class defined in file classdef Person properties Age = 18; Gender = "girl"; Name = "Lily"; endproperties methods %Class method, static method needs to add Static function setName(obj,string) obj.Name = string; endfunction function Intro(obj) fprintf("I'm %s\n",obj.Name); endfunction endmethods endclassdef
python can create classes in the command line, or create classes in the file. If you create a class in the file, you need to import it through import before you can call it in the command line.
>>> class Person: ... Age = 18 ... Gender = "girl" ... Name = "Lily" ... def setName(self, str): ... self.Name = str ... def Intro(self): ... print("I'm",self.Name) ... >>> p = Person() >>> p.setName("wang") >>> p.Intro() I'm wang
Matrix creation and indexing
python's numpy package encapsulates a large number of numerical calculation functions and can perfectly replace Matlab. The following python code defaults to from numpy import*
The following comparison shows numpy Chinese website: Comparison with Matlab
Matlab | Python | Brief description |
---|---|---|
[1 2 3; 4 5 6] | array([[1.,2.,3.], [4.,5.,6.]]) | 2x3 matrix |
zeros(5,1) | zeros([5,1]) | five × 1 zero vector |
ones(5) | ones([5,5]) | five × 5 full 1 matrix |
eye(3) | eye(3) | 3x3 identity matrix |
rand(3,4) | random.rand(3,4) | 3x4 random matrix |
1:5:20 | arange(1,20,5) | [ 1, 6, 11, 16] |
[A,A] | hstack([A,B]) | Transverse splicing |
[A;A] | vstack([a,b]) | Longitudinal splicing |
A(end) | A[-1] | Last element |
A(2,5) | A[1,4] | Returns the elements in the second row and the fifth column |
A(2,:) | A[1] or A[1,:] | Second line |
a(1:5,:) | A[0:5], A[:5] or A[0:5,:] | First five elements |
A(end-4:end,:) | A[-5:] | The last five lines |
A(1:3,5:9) | A[0:3][:,4:9] | Submatrix with rows 1 to 3 intersecting columns 5 to 9 |
A([2,4,5],[1,3]) | A[ix_([1,3,4],[0,2])] | Elements crossed by rows 2, 4 and 5 and columns 1 and 3 |
A(3:2:21,:) | A[2:21:2,:] | Take 1 line every 2 lines from line 3 to line 21 |
A(1:2:end,:) | A[ ::2,:] | Returns the odd rows of a |
A(end: -1:1,:) | A[ ::-1,:] | Row order transpose |
Matrix calculation and operation
In Matlab, the multiplication and division between elements needs to be realized through. While Python does not need it at all.
Matlab | Python | Brief description |
---|---|---|
A.' | A.T | Matrix transpose |
A' | A.conj().T | Conjugate transpose |
A * B | A @ B | Matrix multiplication |
A .* B | a * b | Element multiplication |
A./B | A/B | Element division |
A.^3 | A**3 | The third power of A |
(A>0.5) | (A>0.5) | If the element in A is greater than 0.5, it is True, otherwise it is False |
find(A>0.5) | nonzero(A>0.5) | Position of all elements greater than 0.5 in A |
A(A>0.5) | A[A>0.5] | Returns elements greater than 0.5 in A |
A(A<0.5)=0 | A[A<0.5]=0 | Zero elements less than 0.5 in A |
A(:)=3 | A[:]=3 | Set all values to 3 |
max(max(A)) | A.max() | Maximum element of A |
max(A) | A.max(0) | Maximum element of each column matrix (the maximum value is taken in the direction of the 0th coordinate axis) |
max(A,[],2) | A.max(1) | Maximum element per row matrix |
max(A,B) | maximum(A, B) | Compare elements A and B one by one and return the maximum value in each pair |
norm(A) | sqrt(A @ A) or linalg.norm(v) | 2-norm |
inv(A) | linalg.inv(A) | Inverse of square matrix |
pinv(A) | linalg.pinv(A) | Pseudo inverse of matrix |
rank(A) | linalg.matrix_rank(A) | Rank of matrix |
A\b | linalg.solve(A,b)(A is a square matrix) blinalg.lstsq(A,b)(A need not be a square matrix) | Ax = solution x of B |
fft(A) | fft(A) | Fourier transformation |
ifft(A) | ifft(A) | Inverse Fourier transform |
sort(A) | A.sort() | sort |