numpy 矩阵没有转置

numpy matrix is not getting transposed

转置前后J_vals内容相同。

    theta0_vals = np.linspace(-10, 10, 100) #creates 1D numpy array
    theta1_vals = np.linspace(-1, 4, 100)   #creates 1D numpy array   
    J_vals = np.zeros((len(theta0_vals), len(theta1_vals))) #creates 2D numpy matrix

    for i in range (0, len(theta0_vals)):
        for j in range (0, len(theta1_vals)):
            t = ([theta0_vals[i], theta1_vals[j]])
            J_vals[i,j] = costCompute(x, y, t) #costCompute is user defined function
    np.transpose(J_vals)

以上片段的输出如下:-

转置前

[[ 328.09290555, 316.6648683, 305.44447299 ..., 186.35412584, 195.06735595, 203.98822799]

 [ 323.26504192, 311.92025945, 300.7831189  ..., 189.60197489, 198.39845977, 207.40258658]

 [ 318.47799046, 307.21646275, 296.16257698 ..., 192.89063611, 201.77037576, 210.85775734]

 ..., 

 [  49.81156018, 46.45923561, 43.31455298 ..., 691.41691065, 708.20585345, 725.20243817]

 [  48.94247627, 45.67340647, 42.61197861 ..., 698.62353943 715.49573699  732.57557648]

 [  48.11420452, 44.9283895, 41.95021641 ..., 705.87098036, 722.82643269, 739.98952696]]

转置后

[[ 328.09290555, 316.6648683, 305.44447299 ..., 186.35412584, 195.06735595, 203.98822799]

 [ 323.26504192, 311.92025945, 300.7831189  ..., 189.60197489, 198.39845977, 207.40258658]

 [ 318.47799046, 307.21646275, 296.16257698 ..., 192.89063611, 201.77037576, 210.85775734]

 ..., 

 [  49.81156018, 46.45923561, 43.31455298 ..., 691.41691065, 708.20585345, 725.20243817]

 [  48.94247627, 45.67340647, 42.61197861 ..., 698.62353943, 715.49573699, 732.57557648]

 [  48.11420452, 44.9283895, 41.95021641 ..., 705.87098036, 722.82643269, 739.98952696]]

numpy.transpose 不修改输入数组但 returns 转置数组。

你应该做

J_vals_t = numpy.transpose(J_vals)
print(J_vals_t)

有一种更简单的方法来转置 numpy 数组。只需执行 A.T 即可得到转置矩阵。 请参见以下示例

A=numpy.array([[1,1,1],[2,2,2],[3,3,3]])
A_transpose=A.T

您将得到转置矩阵。