On Sun, Sep 5, 2010 at 7:05 PM, gary ng <[email protected]> wrote:
> What would be the recommended way to do this , say replace every
> element that is odd to '_1' ?

Has anyone shown the solution with the power conj yet?  This is
approperiate if the condition of what to replace depends on the value
of that one element only.

   ]a=: 12 ?...@$ 20
9 8 15 17 4 0 1 2 17 9 3 12
   _1:^:(2&|)"0 a
_1 8 _1 _1 4 0 _1 2 _1 _1 _1 12

This, of course, is more useful when you don't want to replace with a
constant, but with a function of the previous value:

   _1&*^:(2&|)"0 a
_9 8 _15 _17 4 0 _1 2 _17 _9 _3 12

If you want to replace with a constant, then it might be easier to
extract the indices and use the amend conj:

   _1 (I.2|a)} a
_1 8 _1 _1 4 0 _1 2 _1 _1 _1 12

If you don't want to replace with a constant and which elements you
want to replace does not depend only on the values, then item amend
comes quite useful.  Eg. suppose we want to replace all but the first
occurrence of each number.  Then we extract a mask for what we want to
replace:

   ]m=: -.~:a
0 0 0 0 0 0 0 0 1 1 0 0

and then we use item amend to replace:

   m} a,:_1
9 8 15 17 4 0 1 2 _1 _1 3 12
   m} a,:1e3*a
9 8 15 17 4 0 1 2 17000 9000 3 12

There are, of course, lots of other possibilities.

Ambrus
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to