所以我有两个(或更多)向量的笛卡尔积c,a和b。我想从c。
获得[:: i]和b [:: j]的笛卡尔积这意味着新的笛卡尔积将跳过每个第i个项目和每个第j个项目。
例如
veclens = (3,6)
# <code that generates cross product c here> (I have that).
# result:
c = array([
[0,0],
[0,1],
[0,2],
[0,3],
[0,4],
[0,5],
[1,0],
[1,1],
[1,2],
[1,3],
[1,4],
[1,5],
[2,0],
[2,1],
[2,2],
[2,3],
[2,4],
[2,5]])
print c.shape
(18, 2)
samples = (2,2) # so we want every 2nd item a, and every 2nd in b
# this is the function I would like:
d = get_subarray(c, samples, veclens)
# and now d is something like
array([
[0,0],
[0,2],
[0,4],
[2,0],
[2,2],
[2,4]])
任何想法如何编写get_subarray而不从头开始计算数组c(这很昂贵,因为它实际上是在a和b的交叉积上评估的函数)。当然有一些索引技巧?
我正在寻找类似以下的东西,但更通用,更优雅,更快。
def get_subarray(c, samples, veclens):
indexes = []
for i in range(0, veclens[0], samples[0]):
for j in range(0, veclens[1], samples[1]):
indexes.append(i * veclens[1] + j)
return c[indexes]
答案 0 :(得分:0)
以下是使用ix _:
的一般解决方案def get_subarray(c, samples, veclens):
n = len(veclens)
d = c.reshape(veclens+[n])
i = numpy.ix_(*[range(0, l, s) for l,s in zip(veclens,samples)]
return d[i].reshape((-1,n)