0

I want to set values in an array based on an index and using a computation. In numpy I would write the following:

array[array < 0] = 2 * array[array < 0]

Can something like this be achieved with ND4J as well?

Edit: And what about more complicated statements / indexing such as:

array[array2 < 0] = 2 * array3[array2 < 0]

(Assuming dimensions of array1, array2 and array3 match)

user2912328
  • 171
  • 10

1 Answers1

0

Conditional assign is what you would be the closest:

import org.nd4j.linalg.indexing.BooleanIndexing;
import org.nd4j.linalg.indexing.conditions.Conditions;


INDArray array1 = Nd4j.create(new double[] {1, 2, 3, 4, 5, 6, 7});
INDArray array2 = Nd4j.create(new double[] {7, 6, 5, 4, 3, 2, 1});
INDArray comp = Nd4j.create(new double[] {1, 2, 3, 4, 3, 2, 1});
BooleanIndexing.replaceWhere(array1, array2, Conditions.greaterThan(4));

There are quite a few conditions and things you can use in there. I would suggest using the second array and applying your arithmetic you want on a whole array and letting BooleanIndexing replace what you want selecting elements from the second array you pass in.

Adam Gibson
  • 3,055
  • 1
  • 10
  • 12
  • Thanks! So if I understand you correctly then there is no way around performing the computation on the whole array? – user2912328 Feb 03 '22 at 10:58
  • You could apply a lambda yourself manually over the for loop. It works in a mask like format selects the element from the exact sell though. Numpy's doex an indirect lambda. Our underlying software is applied at the c++ level rather than ragged style (eg: 1 off indices) If you want, you are welcome to file an issue: https://github.com/eclipse/deeplearning4j/issues and we can look at a face way to do that. – Adam Gibson Feb 03 '22 at 11:40