4

How can I perform an element-wise multiplication of a numpy-nd-array with an arbitrary double-scalar in C?

I'm searching for a api-function like this:

// C-code
PyArray_MultiplyWithScalar((PyArrayObject *) myarray, double scalar_value);

corresponding to pure numpy:

# pure python
myarray = myarray * scalar_value

My current (bad) solution is to iterate over all entries and perform the normalization manually.

Hensing
  • 421
  • 3
  • 6
  • I don't think there is anything like that. Use `NpyIter_New` to iterate through the array. Otherwise you can convert the scalar_value to an array of course and call the ufunc through python. – seberg May 16 '13 at 21:10
  • 1
    Ah, and you need to set the correct flags, i.e. `NPY_ITER_GROWINNER` and `NPY_ITER_EXTERNAL_LOOP` for best speeds, which gets a bit more involved but it might be worth to learn. – seberg May 16 '13 at 21:13
  • I've seen all these iterators with the flags but I'm hoping for a better/shorter solution :-) I think that increasing the optimized iterator costs a functioncall... – Hensing May 16 '13 at 21:54
  • no it doesn't with external_loop. With it, you will get the innermost loop for yourself to implement, and that innermost loop will often be the whole array. – seberg May 16 '13 at 23:13
  • Did you ever find an answer to this? – JMzance May 16 '17 at 20:15

1 Answers1

0

I don't know the right answer to your question, but if you do a loop in C that should be as fast as it gets, I would even think faster than calling a python api function if you do it right. Doing it that way you can even edit the array in place without the need for additional memory.

Magellan88
  • 2,543
  • 3
  • 24
  • 36
  • I think/hope that numpy has it's own **best way** to iterate over all entries without the need for additional memory. – Hensing May 16 '13 at 16:14