Search code examples
apldyalog

Apply a function to a random row of a matrix


I have a 5x5 matrix M and a function f that operates on vectors. r ← ⊃?⍴M is the index of a random row of M. I need to return a modified version of M without direct assignment (it's important for the larger program) where f is only applied to r⌷M. I'm doing this by mapping across M's rows, returning f⍵ if the row's index matches r, and just if it doesn't. The function I came up with is:

({f(⍣(r = M⍳⍵))⍵}⍤1) M

It works, but it's not ideal. I don't like the r = M⍳⍵ part, because I'm searching for the index of in every cycle. I think it'd make more sense to operate across ⍳5 instead, referencing each row in terms of each in this vector. I can't seem to get this to work though.

Any help making my function less ugly is appreciated.


Solution

  • f@r⊢M­

    Example code:

    M←5 5⍴⍳25
    f←-
    r←⊃?⍴M
    ⎕←f@r⊢M
    

    Example result:

     1  2  3  4   5
    ¯6 ¯7 ¯8 ¯9 ¯10
    11 12 13 14  15
    16 17 18 19  20
    21 22 23 24  25