Matlab中矩阵A(:)操作在Python中的等效实现方法咨询
A(:) in Python Hey there! Let's break down how to get the exact behavior of MATLAB's A(:) in Python, using your 2×3 matrix example as a reference. First, a quick recap: MATLAB's A(:) flattens a matrix column-wise (column-major order) into a 1D array—for your input [[5,6,7],[8,9,10]], that means pulling values from the first column, then the second, then the third, to get [5,8,6,9,7,10].
In Python, NumPy is your go-to library for matrix operations, and there are three straightforward ways to replicate this behavior:
Method 1: Use numpy.ravel() with order='F'
ravel() flattens an array, and the order='F' parameter tells it to use column-major (Fortran-style) ordering—just like MATLAB. This returns a view of the original array when possible (saves memory):
import numpy as np A = np.array([[5, 6, 7], [8, 9, 10]]) flattened = A.ravel(order='F') print(flattened) # Output: [ 5 8 6 9 7 10]
Method 2: Use numpy.flatten() with order='F'
This works almost exactly like ravel(), but it always returns a copy of the array. Use this if you need to modify the flattened array without affecting the original matrix:
import numpy as np A = np.array([[5, 6, 7], [8, 9, 10]]) flattened = A.flatten(order='F') print(flattened) # Output: [ 5 8 6 9 7 10]
Method 3: Use numpy.reshape() with order='F'
You can reshape the matrix to a 1D array by passing -1 (NumPy automatically calculates the correct length) and specifying column-major order:
import numpy as np A = np.array([[5, 6, 7], [8, 9, 10]]) flattened = A.reshape(-1, order='F') print(flattened) # Output: [ 5 8 6 9 7 10]
A quick heads-up
NumPy's default ordering is 'C' (row-major, C-style), which would give you [5,6,7,8,9,10] for your example. So don't forget to add order='F' to match MATLAB's A(:) behavior!
内容的提问来源于stack exchange,提问作者Nikko

