2

Is there a way to multiply or add a scalar to the same row or column in each array of a nested array without a loop? For example I would like to multiply all the values in the 2nd column (or row) of each array by 2 for the sample nested array below.

      (4 3)(5 3)(3 3)⍴¨⊂⍳15
┌────────┬────────┬─────┐
│ 1  2  3│ 1  2  3│1 2 3│
│ 4  5  6│ 4  5  6│4 5 6│
│ 7  8  9│ 7  8  9│7 8 9│
│10 11 12│10 11 12│     │
│        │13 14 15│     │
└────────┴────────┴─────┘
xpqz
  • 3,617
  • 10
  • 16

1 Answers1

2

You can do it without using a :For control structure, but there'll still be an explicit loop in the form of the Each operator (¨):

      a ← (4 3)(5 3)(3 3)⍴¨⊂⍳15  ⍝ naming your array
      2×@2¨ a   ⍝ 2 multiplies at [row] 2 of each
┌────────┬────────┬───────┐
│ 1  2  3│ 1  2  3│1  2  3│
│ 8 10 12│ 8 10 12│8 10 12│
│ 7  8  9│ 7  8  9│7  8  9│
│10 11 12│10 11 12│       │
│        │13 14 15│       │
└────────┴────────┴───────┘
      2+@2⍤1¨ a   ⍝ 2 adds at [element] 2 row-wise of each
┌────────┬────────┬──────┐
│ 1  4  3│ 1  4  3│1  4 3│
│ 4  7  6│ 4  7  6│4  7 6│
│ 7 10  9│ 7 10  9│7 10 9│
│10 13 12│10 13 12│      │
│        │13 16 15│      │
└────────┴────────┴──────┘

The @ operator work on leading axes, the leading axis of a matrix being containing the rows, so the 2nd cell is the 2nd row. The ⍤1 operator restricts the "view" of +@2 to only ever see rows, which are subarrays of rank 1..

Adám
  • 6,573
  • 20
  • 37