MATLAB Answers

0

key generation and inversing

Asked by Elysi Cochin on 8 Mar 2018
Latest activity Edited by 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 ;

  0 Comments

Sign in to comment.

1 Answer

Answer by Roger Stafford on 8 Mar 2018
Edited by Roger Stafford on 8 Mar 2018
 Accepted Answer

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.

  3 Comments

sir how is the working happening.
As you said above "This has the effect of getting the inverse of the Key value".
So i should get [3,6,5,1,2,4]. How will i get the value [3,2,6,1,4,5]. How does it becomes inverse of key?
i'm not clear with that portion. Please could you give me an explanation?
Jan
on 8 Mar 2018
The "key" [4,2,1,5,6,3] can be used to resort a vector. Example:
key = [4,2,1,5,6,3];
S = 'abcdef'
T = S(key); % 'dbaefc'
The 1st element becomes the 4th, the 2nd element remains the 2nd, the 3rd element becomes the 1st, etc. Now you create the "inverse key" such, that it converts T back to S:
invKey(key) = 1:6; % [3,2,6,1,4,5]
This means, the 1st element becomes the 3rd, etc. This is the opposite sorting compared to "key". Finally:
T(invKey) % 'abcdef'
@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.

Sign in to comment.