Reputation: 75
I have following lines of code to create a permutation matrix.
R=zeros(N^2,N^2);
R1=randperm(N^2);
for j=1:N^2
R(j,R1(j))=1;
end
Is there a faster way?
Upvotes: 0
Views: 51
Reputation: 14939
You can use linear indexing like this:
N = 3;
R = zeros(N^2);
R(randperm(N^2) + (0:N^2:(N^4-N^2))) = 1;
This works because the N^2+1
is the first element in the second column, 2*N^2+4
is the fourth element in the third column etc.
Let's define M = N^2
to make the explanation simpler. Now, 0:M:(M^2-M)
creates a matrix [0 M 2*M 3*M ... (M-1)*M]
. By adding R1
you will get a vector with elements [R1(1), M+R1(2) 2*M+R1(3) ... (M-1)*M+R1(M)]
. If you use those numbers as indices, the first number will correspond to row R1(1)
in the first column, the second number will correspond to the R1(2)
in the second column etc.
Now you can assign the value 1
to the R
-matrix in these positions. You might want to have a look at the function ind2sub
to understand how this works. ind2sub
converts the linear indices into the "normal" [rows cols]
indexing style.
pos = randperm(M)+(0:M:(M^2-M))
pos =
1 15 26 31 38 54 59 70 75
[row, col] = ind2sub(size(R), pos)
row =
1 6 8 4 2 9 5 7 3
col =
1 2 3 4 5 6 7 8 9
If you need the R1
variable some other place, you can of course do:
R = zeros(N^2);
R1 = randperm(N^2)
R(R1 + (0:N^2:(N^4-N^2))) = 1;
Upvotes: 1