用Python切片矩阵 [英] Slicing a matrix with Python

查看:134
本文介绍了用Python切片矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将12 * 12矩阵切成24 2 * 3块.输入矩阵为:

I need to slice 12*12 matrix to 24 2*3 pieces. Matrix of input is:

arr = [
[1,0,1,1,1,0,1,1,1,0,1,0],
[0,0,0,1,0,1,1,1,1,0,1,0],
[0,1,1,0,0,0,1,0,1,0,0,0],
[1,0,0,1,0,0,1,1,1,0,1,1],
[0,0,0,1,0,0,0,1,1,1,1,0],
[0,0,0,0,0,1,1,0,0,0,0,1],
[1,0,1,0,0,0,1,1,0,0,1,1],
[0,0,1,1,0,1,0,1,1,0,1,0],
[0,1,0,0,0,0,1,0,1,0,0,1],
[1,1,0,1,0,1,0,1,0,1,0,0],
[0,0,1,1,1,1,0,1,0,1,1,1],
[0,0,0,0,1,0,0,0,1,1,0,0]]

我尝试使用numpy Matrix实现任务:

I try to achieve the task with numpy Matrix:

from sympy import Matrix
Matrix(arr)[:3,:2]

但是它只会从原始矩阵中切出一片.

But it will give only one slice from the original matrices.

Matrix([
[1, 0],
[0, 0],
[0, 1]])

将12 * 12矩阵切成2 * 3块的便捷方法是什么?我还需要具有原始尺寸的3 * 2,但是假设在准备好第一个尺寸之后很容易.

What is the convenient way to slice 12*12 matrices to 2*3 pieces? I also need to have dimensions 3*2 of the original, but suppose it's easy after getting the first one ready.

推荐答案

arr = [
[1,0,1,1,1,0,1,1,1,0,1,0],
[0,0,0,1,0,1,1,1,1,0,1,0],
[0,1,1,0,0,0,1,0,1,0,0,0],
[1,0,0,1,0,0,1,1,1,0,1,1],
[0,0,0,1,0,0,0,1,1,1,1,0],
[0,0,0,0,0,1,1,0,0,0,0,1],
[1,0,1,0,0,0,1,1,0,0,1,1],
[0,0,1,1,0,1,0,1,1,0,1,0],
[0,1,0,0,0,0,1,0,1,0,0,1],
[1,1,0,1,0,1,0,1,0,1,0,0],
[0,0,1,1,1,1,0,1,0,1,1,1],
[0,0,0,0,1,0,0,0,1,1,0,0]]

from sympy import Matrix
row_skip = 3
column_skip = 2

for i in xrange(0, len(arr), row_skip):
    for j in xrange(0, len(arr[0]), column_skip):
        print Matrix(arr)[i:i+row_skip, j:j+column_skip]

输出:

Matrix([[1, 0], [0, 0], [0, 1]])
Matrix([[1, 1], [0, 1], [1, 0]])
Matrix([[1, 0], [0, 1], [0, 0]])
Matrix([[1, 1], [1, 1], [1, 0]])
Matrix([[1, 0], [1, 0], [1, 0]])
Matrix([[1, 0], [1, 0], [0, 0]])
Matrix([[1, 0], [0, 0], [0, 0]])
Matrix([[0, 1], [0, 1], [0, 0]])
Matrix([[0, 0], [0, 0], [0, 1]])
Matrix([[1, 1], [0, 1], [1, 0]])
Matrix([[1, 0], [1, 1], [0, 0]])
Matrix([[1, 1], [1, 0], [0, 1]])
Matrix([[1, 0], [0, 0], [0, 1]])
Matrix([[1, 0], [1, 1], [0, 0]])
Matrix([[0, 0], [0, 1], [0, 0]])
Matrix([[1, 1], [0, 1], [1, 0]])
Matrix([[0, 0], [1, 0], [1, 0]])
Matrix([[1, 1], [1, 0], [0, 1]])
Matrix([[1, 1], [0, 0], [0, 0]])
Matrix([[0, 1], [1, 1], [0, 0]])
Matrix([[0, 1], [1, 1], [1, 0]])
Matrix([[0, 1], [0, 1], [0, 0]])
Matrix([[0, 1], [0, 1], [1, 1]])
Matrix([[0, 0], [1, 1], [0, 0]])

您可以根据需要更改行跳过和列跳过

you can change row skip and column skip as you want

这篇关于用Python切片矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆