permutation matrix in Q

I’m trying to write a Q function that generates a permutation matrix (a boolean matrix with only a single 1 in each row and column, zeroes elsewhere). The function below gives me the “assign” error on the first assignment statement inside the do-loop. This should mean that I’m misusing a reserved word, but I don’t see how that could be the case here. Also, as an old APLer, I thought that it should be possible to write this function without an explicit loop, but I can’t figure out how.

permutation:{

j:(neg x)?x;

i:til x;

a:(x;x)#0;

k:0;

do[

x;

a[i[k]][j[k]]:1;

k:k+1;

];:a}

You’re getting an 'assign because you’re trying to assign a number to another number, essentially.

You want functional amend. You can turn the folllowing into a function, I’m just hard coding 6 as the matrix width/height for now:

q)m:(6;6)#0

q)r

2 4 1 0 3 5

q)r:-6?6

q)m

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

0 0 0 0 0 0

q)r

3 4 2 0 5 1

q).[`m;;:;1] each til[6],'r

mmmmmm

q)m

0 0 0 1 0 0

0 0 0 0 1 0

0 0 1 0 0 0

1 0 0 0 0 0

0 0 0 0 0 1

0 1 0 0 0 0

{@'[(x,x)#0;neg?x;:;1]}

Manish and Attila:

Elegant solutions! Thanks!

-Stu