# key generation and inversing

23 views (last 30 days)
Elysi Cochin on 8 Mar 2018
Edited: Roger Stafford on 8 Mar 2018
i generate a random key using the below line
Key = randperm(n*m);
please can someone explain what does the below two line denote. How to explain the below two lines
invKey = 1:(n*m);
invKey (Key) = invKey ;

Roger Stafford on 8 Mar 2018
Edited: Roger Stafford on 8 Mar 2018
Your code first puts the successive integers from 1 to n*m in the vector 'invKey'. Then it subjects them to a randomly determined permutation as give by 'Key'. This has the effect of getting the inverse of the Key value. That is, suppose n*m = 6, and suppose 'randperm' yields Key = [4,2,1,5,6,3]. Then invKey is initially [1,2,3,4,5.6]. After the invKey(Key)=invKey step, invKey will contain [3,2,6,1,4,5] which is the inverse of Key.
Roger Stafford on 8 Mar 2018
@Elysi: In the example I gave you with Key = [4,2,1,5,6,3] and invKey = [3,2,6,1,4,5], they are inverses of one another in the sense that
Key(invKey) = 1:6
and
invKey(Key) = 1:6
You can easily check that for yourself. In your code you wrote
invKey(Key) = invKey
which at that point was the same as writing
invKey(Key) = 1:6 (or in your example 1:n*m)
That assures one of the above two assertions. The other assertion follows from
Key(invKey(Key)) = Key(1:6) = Key
Thus Key(invKey(Key)) is identical it just Key. Then for example
Key(invKey(Key(1))) = Key(1)
which means that Key(invKey(4)) = 4. Similarly, Key(invKey(n)) will map to n for any n from 1 to 6. In other words
Key(invKey) = 1:n
which is the other assertion.
This technique is often used in getting the inverse of such permutations as the list of indices when doing a sort:
[y,p] = sort(x);
To get the inverse of p one can do this:
n = length(x)
q = 1:n;
q(p) = q; % (<-- Corrected)
The permutation q is now the inverse of p, and therefore has the property that p(q) = 1:n and q(p) = 1:n.