14

操作矩阵时,更改它们的形状通常很方便。例如,要将 N x M 大小的矩阵转换为长度为 NX M 的向量。在 MATLAB 中存在整形函数:

RESHAPE(X,M,N) 返回 M×N 矩阵,其元素从 X 中按列获取。如果 X 没有 M*N 元素,则会导致错误。

在矩阵和向量之间转换的情况下,我可以使用 Mathematica 函数Flatten,它利用了 Mathematica 的矩阵嵌套列表表示。举个简单的例子,假设我有一个矩阵 X:

4x4 矩阵

使用Flatten [X] 我可以得到向量 {1,2,3,...,16}。但是更有用的是类似于应用 Matlab 的reshape (X,2,8) 这将导致以下矩阵:

4x4 矩阵

只要维度等于 N*M,这将允许创建任意矩阵。据我所知,没有任何内置的东西让我想知道是否有人没有编写自己的 Reshape 函数。

4

5 回答 5

20
Reshape[mtx_, _, n_] := Partition[Flatten[mtx], n]
于 2010-03-18T06:53:18.647 回答
12

ArrayReshape正是这样做的。

于 2013-07-09T04:52:45.663 回答
5
Reshape[list_, dimensions_] := 
First[Fold[Partition[#1, #2] &, Flatten[list], Reverse[dimensions]]]

示例用法:

In: Reshape[{1,2,3,4,5,6},{2,3}]

Out: {{1,2,3},{4,5,6}}

这适用于任意深度的数组。

于 2012-05-04T20:43:44.510 回答
3

我知道这是一个旧线程,但为了存档和谷歌搜索,我有一个更通用的方法,允许将长度 m*n*... 列表转换为 m*n*... 数组:

Reshape[list_, shape__] := Module[{i = 1},
  NestWhile[Partition[#, shape[[i]]] &, list, ++i <= Length[shape] &]
  ]

例如:

In:= Reshape[Range[8], {2, 2, 2}]

Out:= {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}
于 2012-04-05T13:13:46.467 回答
0

现在还有一个新函数 ArrayReshape[]。

例子:

{{1, 2, 3}, {4, 5, 6}} // MatrixForm

ArrayReshape[{{1, 2, 3}, {4, 5, 6}}, {3, 2}] // MatrixForm
于 2017-09-10T13:18:39.550 回答