On Sun, Feb 6, 2022 at 2:24 PM Andrew P <[email protected]> wrote:
> I am trying to learn how to manipulate tables of numbers in J coming from a
> NumPy/Python background. Assuming *mat* is a 10x10 matrix, that's what I
> have figured out so far:
>
> - Replace values equal to 1 with 10
> (mat e. 1) } mat ,: 10
That works, and so does the mechanism Henry Rich suggested. And,
there are other ways. For example:
([ + (10-1) * (=&1)) mat
> - Replace all non-multiples of 5 with _
> (-. 0 = mat |~ 5) } mat ,: _
And arithmetic will also work here.
((% * *@[) 0 = 5&|) mat
Though if mat contains no negative numbers, that could be simplified to
(% 0 = 5&|) mat
> - Multiply each column by its index
> mat (*" 1) i. 10
> - Multiply each row by its index
> mat (*" 0) i. 10
Or, more generally (for arbitrary shaped mat)
(* i.@#) mat
(*"1 i.@{:@$) mat
> - Replace the second column with 0
> 0 (1) }"1 mat
> - Replace the second column with 0 (another way)
> 0 (< (i.10); 1 ) } mat
Or
(*"1 (1)~:i.@{:@$)mat
> - Take the diagonal of the matrix
> (<0 1)&|: mat
Indeed, and that's the best way, though you could also use
(, {~ $ (#."1 0 i.)<./@$)mat
> Now, there are some tasks that I can do in NumPy but haven't found how to
> do in J. For instance:
> - Add 1 to each value in the first column
> x[:,1] += 1
You've already gotten some answers here. I'll repeat them for emphasis
and threw in a few others:
(1 + 0{"1 mat) 0}"0 1 mat
(1 + 0{"1 mat) 0}"_1 mat
(1+0{])`0:`]}"1~ mat
mat +"1 (0=i.10)
(+"1 0:=i.@{:@$) mat
> - Add 1 to each value in the third row
> x[3,:] += 1
And the answers here are similar:
(1 + 2{mat) 2} mat
(1 + 2{])`2:`]}~ mat
mat+2=i.10
(+ 2= i.@#) mat
> In each of those cases, I am selecting the cells by their indexes rather
> than their values, and am using the existing values to generate the new
> ones. Is that possible in J?
>
> I would also like to figure out how to modify nontrivial sequences of
> indexes, for instance, diagonals or cells where both the row index and the
> column index are even numbers. Where should I start if I want to do that
> kind of thing?
I would start either by calculating the relevant indices or
constructing a bitmask representing those positions. (Or maybe both,
since having multiple approaches to a problem can sometimes be
useful.)
But also think for a moment about the nature of the specification. Do
you want even numbers where 0 would have been the first index or do
you want even numbers where 1 would have been the first index. In
other words:
(= * 0=2&|)i.#mat
vs
(= * 2&|)i.#mat
Anyways, you might wind up with an expression like
(, {~ $ (#."1 0 i.&<.&.-:)<./@$)mat
I hope this helps,
--
Raul
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm