jima
jima

Reputation: 48

Understanding J From

In J:

a =: 2 3 $ 1 2 3 4 5 6

Gives:

1 2 3
4 5 6

Which is a 2 3 shaped array.

If I do:

0 1 { a

I (noting that 0 1 is a 2 shaped list) expected to have back:

1 2 3 4 5 6

But got the following instead:

1 2 3
4 5 6

Reading the documentation I was expecting the shape of the index to kinda govern the shape of the answer.

Can someone clarify what I am missing here?

Upvotes: 3

Views: 102

Answers (2)

Dane
Dane

Reputation: 1211

Higher-dimensional arrays may help make this clear. An array with n dimensions has items with n-1 dimensions. When you select an item from ({) a three-dimensional array, your result is a two-dimensional array:

   1 { i. 5 3 4
12 13 14 15
16 17 18 19
20 21 22 23

When you select multiple items from an array, the items are assembled into a new array, using each atom of x to select a item of y. This might be where you picked up the idea that the shape of x affects the shape of the result.

   2 1 0 2 { 'set'
test
   $ 2 1 0 2
4
   $ 'test'
4

The dimensions of the result is equal to the dimensions of x plus the dimensions of the items of y. So, if you have a two-dimensional x taking two-dimensional items from a three-dimensional y, you will have a four-dimensional result:

   (2 2 $ 1 1 0 1) { i. 5 3 4
12 13 14 15
16 17 18 19
20 21 22 23

12 13 14 15
16 17 18 19
20 21 22 23


 0  1  2  3
 4  5  6  7
 8  9 10 11

12 13 14 15
16 17 18 19
20 21 22 23
   $ (2 2 $ 1 1 0 1) { i. 5 3 4
2 2 3 4

One final note: the monadic Ravel (,) will reduce the result to a list (one-dimensional array).

   , 0 1 { 2 3 $ 1 2 3 4 5 6
1 2 3 4 5 6
   , i. 2 2 2 2
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Upvotes: 5

bob
bob

Reputation: 4302

From ({) selects the items of a noun. For 2 3 $ 1 2 3 4 5 6 the items are the two rows because items are the components that make up the noun.

   [ a=. 2 3 $ 1 2 3 4 5
1 2 3
4 5 1
   0 { a
1 2 3

If you just had 1 2 3 then the items would be the individual atoms.

   [ b=. 1 2 3
1 2 3
   0 { b
1

If you used 1 3 $ 1 2 3 then there is only one item and the result would be

   [ c=. 1 3 $ 1 2 3
1 2 3
   0 { c
1 2 3

The number of items can be found with Tally (#), and is the lead dimension of the Shape ($) of the noun.

   $ a
2 3
   $ b
3
   $ c
1 3

   # a
2
   # b
3
   # c
1

Upvotes: 2

Related Questions