key generation and inversing

조회 수: 3 (최근 30일)
Elysi Cochin
Elysi Cochin 2018년 3월 8일
편집: Roger Stafford 2018년 3월 8일
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
Roger Stafford 2018년 3월 8일
편집: Roger Stafford 2018년 3월 8일
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
Jan
Jan 2018년 3월 8일
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'
Roger Stafford
Roger Stafford 2018년 3월 8일
편집: Roger Stafford 2018년 3월 8일
@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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by