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:
The height and width of the given matrix is in range [1, 100].
The given r and c are all positive.

方法1:利用商与余数

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

方法2:

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

            if((i+1)%c==0){
                res.push_back(row);
                row.clear();
            }

        }
        return res;

    }
};
### Python 中 `reshape` 的用法 在 NumPy 和 TensorFlow/Keras 等库中,`reshape` 是一种非常重要的操作方法,用于改变数组或张量的形状而不改变其数据。以下是关于 `reshape` 的详细介绍: #### 基本概念 NumPy 提供了一个简单的方法来调整数组的维度——即通过调用 `.reshape()` 方法。此函数允许用户指定新的形状参数,只要新形状中的总元素数量与原始形状一致即可[^1]。 对于 Keras 或 TensorFlow 用户来说,在构建神经网络模型之前通常需要对输入数据进行预处理,其中包括可能涉及图像或其他多维结构的数据重塑过程。例如,如果要训练一个 CNN 模型,则需确保输入层接收的是四维张量形式(样本数×高度×宽度×通道),此时就可能会用到 `reshape` 函数。 #### 使用示例 下面是几个具体的例子展示如何正确运用 `numpy.reshape()` 来转换不同类型的矩阵: ```python import numpy as np # 创建一维向量 a = np.arange(6) print("Original Array:") print(a) b = a.reshape((2,3)) # 将原有一维数组转成二维表格状 c = b.reshape(-1) # 反之亦可恢复为扁平化的一维列表 print("\nReshaped into 2x3 Matrix:") print(b) print("\nFlattened back to one dimension:") print(c) ``` 上述代码片段展示了怎样把长度为6的一维序列分别重构成具有两行三列的新布局以及再次拉直还原的过程。 当涉及到更复杂的场景比如图片分类任务时,假设每张图像是灰度模式下大小固定为28*28像素点,并且整个批次共有N个这样的实例待分析;那么就需要把这些单独存在的个体组合起来形成统一规格的大批量送入DNN内部计算单元当中去完成后续工作流。具体做法如下所示: ```python images = ... # shape: (N, 28, 28), where N is the number of images. reshaped_images = images.reshape(N, 28 * 28) # Flatten each image. model_input = reshaped_images.astype('float32') / 255.0 # Normalize pixel values between 0 and 1. ``` 这里先是对单幅影像执行展平动作再标准化数值范围以便于提高收敛速度并减少梯度消失现象发生几率。 #### 错误排查技巧 有时开发者会遇到一些常见的错误提示信息,如“cannot reshape array”,这往往是因为尝试设定的目标尺寸无法容纳源对象内的全部项目所引起的结果不匹配问题。因此务必确认两者之间存在相等关系后再继续下一步骤操作。 另外值得注意一点就是负号标记位置的选择也会影响最终呈现出来的效果。“-1”作为占位符代表自动推导该轴应有的确切数目从而简化手动计算负担的同时还增强了灵活性。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值