Reshape the Matrix

来源:互联网 发布:ipad从哪里下载软件 编辑:程序博客网 时间:2024/05/20 18:19

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 and columnnumber 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.

var matrixReshape = function(nums, r, c) {    var index = r * c;    var nCol = nums[0].length;    if(nums.length * nCol !== index)         return nums;    var reshape = [];    for (var k = 0; k < r; k++)        reshape[k] = [];    for (var i = 0; i < r * c; i ++)        reshape[Math.floor(i / c)][i % c] = nums[Math.floor(i / nCol)][i % nCol];//二维数组用一个变量进行遍历    return reshape;};


原创粉丝点击