Generate random permutation matrix

I am trying to generate a random square matrix A of dimension n that has one and only one 1 per row and column. My idea is the following, but as a result I get a matrix of all 1s. What am I doing wrong?
A = zeros(n);
p = randperm(n);
x = 1:n;
p = p';
x = x';
A(p,x) = 1;

回答 (2 件)

James Tursa
James Tursa 2017 年 7 月 1 日

4 投票

Another way:
A = eye(n);
A = A(randperm(n),:);
Star Strider
Star Strider 2017 年 7 月 1 日

0 投票

See if this does what you want:
n = 5; % Set Matrix Size
p = randi([2 n], n); % Create Matrix EXCLUDING ‘1’
x1 = sub2ind(size(p), randperm(n), randperm(n)); % Create Linear Indices For ‘1’
p(x1) = 1; % Put ‘1’ Randomly In Each Row, Column
Experiment to get the result you want.

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

2017 年 7 月 1 日

回答済み:

2017 年 7 月 1 日

Community Treasure Hunt

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

Start Hunting!

Translated by