matlab函数之reshape()
reshape - 重构数组
功能:
B = reshape(A, sz);
按矢量sz定义的维度(包括行数 列数 维数)重构矩阵A来得到矩阵B
实现原理
先将矩阵A先排列成一列(结果感受就是按列优先排列),再按照矢量sz定义大小的行数切割
结构及实例
A = rand(4,5)
0.3537 0.6694 0.6692 0.3119 0.8322
0.6230 0.1045 0.5429 0.9518 0.3994
0.6557 0.4872 0.5621 0.9596 0.4807
0.1019 0.2323 0.9449 0.1287 0.2518
1. B = reshape(A, m, n)
返回m * n的矩阵 (m:行数,n:列数)
B = reshape(A, 10, 2)
0.3537 0.5621
0.6230 0.9449
0.6557 0.3119
0.1019 0.9518
0.6694 0.9596
0.1045 0.1287
0.4872 0.8322
0.2323 0.3994
0.6692 0.4807
0.5429 0.2518
2. B = reshape(A, m, n, p)
返回m * n * p的矩阵(m:行数,n:列数, p:维度)
B = reshape(A, 5, 2, 2)
B(:,:,1) =
0.3537 0.1045
0.6230 0.4872
0.6557 0.2323
0.1019 0.6692
0.6694 0.5429
B(:,:,2) =
0.5621 0.1287
0.9449 0.8322
0.3119 0.3994
0.9518 0.4807
0.9596 0.2518
3. B = reshape(A, size)
返回和矢量size维度一致的矩阵
-
B = reshape(A, [2,5,2])
sz:[2,5,2]B(:,:,1) =
0.3537 0.6557 0.6694 0.4872 0.6692
0.6230 0.1019 0.1045 0.2323 0.5429B(:,:,2) =
0.5621 0.3119 0.9596 0.8322 0.4807
0.9449 0.9518 0.1287 0.3994 0.2518 -
B = reshape(A, [1,5,2,2])
sz:[1,5,2,2]
B(:,:,1,1) =0.3537 0.6230 0.6557 0.1019 0.6694
B(:,:,2,1) =
0.1045 0.4872 0.2323 0.6692 0.5429
B(:,:,1,2) =
0.5621 0.9449 0.3119 0.9518 0.9596
B(:,:,2,2) =
0.1287 0.8322 0.3994 0.4807 0.2518
注意点
-
得到的矩阵B中的元素和A相同
-
排列顺序列优先(先按列取数据,再按照size维度先按列排列)
==>所以中间不管经过多少次reshape,最后只要size矢量大小和size(A)相同,就能还原回A。以以上的例子B = reshape(A, [2,5,2])来说,C = reshape(B, size(A))
C =
0.3537 0.6694 0.6692 0.3119 0.8322
0.6230 0.1045 0.5429 0.9518 0.3994
0.6557 0.4872 0.5621 0.9596 0.4807
0.1019 0.2323 0.9449 0.1287 0.2518
==> 和最初定义的A相同 -
prod(sz)必须和numel(A)相同,即元素数量要相同,否则会报错
【说明】prod(sz): 矢量sz元素的乘积, numel(A): 数组A中元素个数(20))
-
矢量size至少包含2个元素,否则报错
-
如果应用中想按行顺序优先排列,可以先对A进行转置,即reshape(a`,sz),或者得到结果之后再转置
A =0.3537 0.6694 0.6692 0.3119 0.8322
0.6230 0.1045 0.5429 0.9518 0.3994
0.6557 0.4872 0.5621 0.9596 0.4807
0.1019 0.2323 0.9449 0.1287 0.2518
B = reshape(A’,[4,5])
B =0.3537 0.8322 0.9518 0.5621 0.2323
0.6694 0.6230 0.3994 0.9596 0.9449
0.6692 0.1045 0.6557 0.4807 0.1287
0.3119 0.5429 0.4872 0.1019 0.2518
注意到排列顺序是行优先