Weave inline typecasting (python)
The following can do the whole thing you are after:
def transpose(lines): code = """ for(int i = 0; i < x; i++) { for(int j = 0; j < N; j++) { out[j + i * N] = atof(lines[j][i]); // OUT2(i, j) = atof(lines[j][i]); } } """ N = len(lines) x = len(lines[0]) out = np.empty((x, N), dtype=np.float64) weave.inline(code, ['lines', 'N', 'x', 'out']) return out>>> matrix = [['0.5', '0.1', '0.7'],['0.2','0.2', '0.4']]>>> matrix[['0.5', '0.1', '0.7'], ['0.2', '0.2', '0.4']]>>> transpose(matrix)array([[ 0.5, 0.2], [ 0.1, 0.2], [ 0.7, 0.4]])
Aside from constantly forgetting ;
after something like 6 years without writing any C, I had a lot of trouble figuring out what out
was turning into inside the C++ code, and in the end it is a pointer to the data itself, not to a PyArrayObject
as the documentation states. There are two variables defined by weave that are available for use, out_array
and py_out
, which are of type PyArrayObject*
and PyObject*
respectively.
I have left an alternative version of the assignment commented out: weave automatically defines macros <VAR>1
, <VAR>2
, <VAR>3
, and <VAR>4
to access items of arrays of the corresponding number of dimensions.