0

I am trying to write a function for the dyadic productin cython. The way I imagined it to work was by giving to equal-sized arrays from python into the cython file, which then multiplies the components and puts them into the matrix I created beforehand.

However, in order to create a matrix of fitting size, I need to extract the input arrays' size first, which it won't let me do and gives me "Not allowed in a constant expression" instead. I read the answer in Cython: creating an array throws "not allowed in a constant expression" which explains my mistake, but does not give a solution that works for me. What is the right way to do this?

This is how I tried to implement it:

def dyadicproduct(np.ndarray[long, ndim=1, mode="c"] x not None, np.ndarray[long, ndim=1, mode="c"] y not None):

    cdef int xsize 
    xsize = len(x)
    cdef double z[xsize][xsize]

    for i in range(xsize):
        z[i][i] = x[i]*y[i]
        for j in range(xsize):
            if j != i:
                z[i][j] = x[i]*y[j]
    return z
RickJames
  • 25
  • 1
  • 5
  • 2
    And why the suggested malloc/free solution doesn’t work for you? – ead Jan 23 '19 at 21:06
  • 1
    You need to allocate the memory on the heap. I would use typed memoryviews as they have a nicer API than using raw C pointers. – ngoldbaum Jan 23 '19 at 21:16
  • Thank you for your comments, but coming from Python programming I guess I was naively hoping there would be a more straight forward possibility. I'll look into the malloc/free solution. – RickJames Jan 24 '19 at 09:56
  • I could/should use cython-arrays in this case: https://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html#cython-arrays – ead Jan 24 '19 at 15:43
  • Or just a Numpy array. Since you return it anyway it might be as well be something allocated in Python to save expensive conversions. – DavidW Jan 24 '19 at 17:50
  • I indeed decided to go with a Numpy array instead for exactly that reason @DavidW. It won't make much of a difference timewise. – RickJames Jan 25 '19 at 11:10

0 Answers0