Fast iterate over matrix columns with ctypes

let A be the matrix

import numpy as np
A = np.matrix([[3.0, 1.0, 2.0, 0.0], [2.0, 1.0, 3.0, 1.0], [0.0, 2.0, 0.0, 3.0]])

[[ 3.  1.  2.  0.]
 [ 2.  1.  3.  1.]
 [ 0.  2.  0.  3.]]

I came across a complex library (based on the ctypes interface), except that I give pointers to the columns of the matrix, for example:

import ctypes

for j in range(0,4):
    a = np.copy(A[:,j])
    lib.DoSomething(a.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))

Obviously, I try to avoid copying the column into the variable a. Probably have a lot of smart ideas? Maybe I need to transpose and copy the matrix? Or is there a way I can save it in a column?

Thomas

+4
source share
2 answers

You can keep the matrix in Fortran order, so the columns are contiguous. Then just pass the view to this adjacent column.

A = np.array([[3.0, 1.0, 2.0, 0.0], [2.0, 1.0, 3.0, 1.0], [0.0, 2.0, 0.0, 3.0]], order='F')
for j in range(0, 4):
    a = A[:, j]

, np.matrix, . -.

+4

numpy . , :

EDIT: , , - order='F', .

import numpy as np

# avoid matrix and define the dtype at the start so you don't have an extra copy
A = np.array([[3.0, 1.0, 2.0, 0.0], [2.0, 1.0, 3.0, 1.0], [0.0, 2.0, 0.0, 3.0]],dtype="float64",order="F")

for row in A.transpose():
    lib.DoSomething(np.ctypeslib.as_ctypes(row))
+2

Source: https://habr.com/ru/post/1535897/


All Articles