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

 

这道题让我们实现矩阵大小的重塑,也就是实现Matlab中的reshape函数,博主也经常使用matlab,对这个函数还是比较的熟悉的。对于这种二维数组大小重新非配的问题的关键就是对应位置的坐标转换,最直接的办法就是先把原数组拉直,变成一条直线,然后再组成新的数组。所以这道题我们先判断给定数组是否能重塑成给定的大小,就是看两者的元素总数是否相同,直接行数乘以列数即可,然后我们新建一个目标大小的数组,并开始遍历,对于每个位置,我们先转为拉直后的一维坐标,然后在算出在原数组中的对应位置赋值过来即可,参见代码如下:

 

解法一:

复制代码
class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        int m = nums.size(), n = nums[0].size();
        if (m * n != r * c) return nums;
        vector<vector<int>> res(r, vector<int>(c));
        for (int i = 0; i < r; ++i) {
            for (int j = 0; j < c; ++j) {
                int k = i * c + j;
                res[i][j] = nums[k / n][k % n];
            }
        }
        return res;
    }
};
复制代码

 

下面这种方法整体思路和上面没啥区别,但是只使用了一个循环,直接就是遍历拉直后的一维数组的坐标,然后分别转换为两个二维数组的坐标进行赋值,参见代码如下:

 

解法二:

复制代码
class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        int m = nums.size(), n = nums[0].size();
        if (m * n != r * c) return nums;
        vector<vector<int>> res(r, vector<int>(c));
        for (int i = 0; i < r * c; ++i) {
            res[i / c][i % c] = nums[i / n][i % n];
        }
        return res;
    }
};
复制代码

 


后面单循环自己写的:

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        int a=nums.size(),b=nums[0].size();
        if(a*b!=r*c)
            return nums;
           vector<vector<int>> res(r, vector<int>(c));
         for (int i = 0; i < r*c; ++i) {
                res[i/c][i%c] = nums[i/ b][i % b];
        }
        return res;
    }
};



### 实现矩阵重塑的方法 在编程中,矩阵重塑是一种常见的操作,通常用于调整数据结构以便于后续处理。以下是几种常见编程语言中的实现方式。 #### Python 中的 NumPy 库 NumPy 是一种强大的科学计算库,在其中可以轻松完成矩阵重塑的操作。`numpy.reshape()` 函数允许用户改变数组形状而不更改其数据[^4]。 ```python import numpy as np # 创建一个一维数组 array = np.array([1, 2, 3, 4, 5, 6]) # 将一维数组重塑为二维数组 (2x3) reshaped_array = array.reshape(2, 3) print(reshaped_array) ``` 上述代码展示了如何通过 `reshape` 方法将原始的一维数组转换成指定大小的二维数组。需要注意的是,新形状的总元素数量必须等于原数组的元素总数[^4]。 #### MATLAB 中的 Reshape 功能 MATLAB 提供了一个内置函数叫做 `reshape` 来重新排列向量或者矩阵的数据到一个新的维度上而保持原有顺序不变[^5]。 ```matlab % 原始列向量 vector = [1; 2; 3; 4; 5; 6]; % 转换成 2 行 3 列的形式 newMatrix = reshape(vector, 2, 3); disp(newMatrix); ``` 这段脚本说明了怎样利用 MATLAB 的 `reshape` 把垂直方向上的矢量变成具有两行三列的新布局形式[^5]。 #### TensorFlow/Keras 下张量变形 对于深度学习框架如TensorFlow 或 Keras来说,它们也支持类似的变换功能来适应神经网络层间输入输出规格的要求[^6]。 ```python from tensorflow import keras import numpy as np input_data = np.random.rand(100).reshape((10, 10)) # 构建随机初始数据集 layer_reshape = keras.layers.Reshape(target_shape=(5, 2))(keras.Input(shape=(10,))) model = keras.models.Sequential([ layer_reshape, ]) output = model.predict(input_data) print(output.shape) # 输出应显示新的尺寸配置 ``` 这里定义了一种模型架构片段,它接受固定模式下的批量样本作为入口,并应用重设指令将其映射至另一组特定参数设定之中[^6]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值