在Numpy中通过逻辑索引获取矩阵的网格 [英] Getting a grid of a matrix via logical indexing in Numpy

查看:122
本文介绍了在Numpy中通过逻辑索引获取矩阵的网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用numpy重写函数,该函数最初在MATLAB中.在MATLAB中有一个逻辑索引部分,如下所示:

I'm trying to rewrite a function using numpy which is originally in MATLAB. There's a logical indexing part which is as follows in MATLAB:

X = reshape(1:16, 4, 4).';
idx = [true, false, false, true];
X(idx, idx)

ans =

     1     4
    13    16

当我尝试使用numpy制作索引时,我无法获得正确的索引编制:

When I try to make it in numpy, I can't get the correct indexing:

X = np.arange(1, 17).reshape(4, 4)
idx = [True, False, False, True] 
X[idx, idx]
# Output: array([6, 1, 1, 6])

通过逻辑索引从矩阵中获取网格的正确方法是什么?

What's the proper way of getting a grid from the matrix via logical indexing?

推荐答案

您还可以这样写:

>>> X[np.ix_(idx,idx)]
array([[ 1,  4],
       [13, 16]])

这篇关于在Numpy中通过逻辑索引获取矩阵的网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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