[Array] 566. Reshape the Matrix

 

In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.

You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number andcolumn number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

Example 1:

Input: 
nums = 
[[1,2],
 [3,4]]
r = 1, c = 4
Output: 
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

 

Example 2:

Input: 
nums = 
[[1,2],
 [3,4]]
r = 2, c = 4
Output: 
[[1,2],
 [3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.

 

Note:

  1. The height and width of the given matrix is in range [1, 100].
  2. The given r and c are all positive.

思路:本题的意思是将一个m*n维数组转换成l*c维,难点在于遍历嵌套vector元素、求vector的大小、初始化嵌套vector、按照数组行列输出等。

代码:

vector<vector<int>>matrixreshape(vector<vector<int>& nums, int r, int c>){

size_t m = nums.size;//vector外层嵌套,即为行

size_t n = nums[0].size;//vector内层嵌套,即为列
if(r * c != m * n)
return nums;
else{
int k =0;
vector<vector<int>>tmp(r, vector<int>(c, 0));//将tmp初始化为r行c列的全零二维数组
for(size_t i = 0; i < m; i++){
for(size_t j = 0; j < n; j++){
tmp[k / c][k % c] = nums[i][j];//按照c列输出,不用担心r行,因为c*r=k
k++;
}
}
return tmp;
}

}

vector初始化:

/vector<T> v(n,i)形式,v包含n 个值为 i 的元素
 vector<int> ivec(10,0);

 //vector<T> v(v1)形式,v是v1 的一个副本

 vector<int> ivec1(ivec);

 //vector<T> v(n)形式,v包含n 个值初始化的元素
 vector<int> ivec2(10);

 

下面是Mat中的reshape

摘自:http://blog.csdn.net/monologue_/article/details/8659632

只是在逻辑上改变矩阵的行列数或者通道数,没有任何的数据的复制,也不会增减任何数据,因此这是一个O(1)的操作,它要求矩阵是连续的。

C++: Mat Mat::reshape(int cn, int rows=0 const)

cn:目标通道数,如果是0则保持和原通道数一致;

rows:目标行数,同上是0则保持不变;

改变后的矩阵要满足 rows*cols*channels  跟原数组相等,所以如果原来矩阵是单通道3*3的,调用Reshape(0,2)是会报错的,因为3*3*1不能被2*1整除。

应用:在提取特征时,往往需要把特征矩阵变成一个行向量

posted @ 2017-08-02 14:43  两猿社  阅读(140)  评论(0编辑  收藏  举报