# Generate random permutation matrix

조회 수: 202(최근 30일)
Viviana Arrigoni 2017년 7월 1일
답변: James Tursa 2017년 7월 1일
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 2017년 7월 1일
Another way:
A = eye(n);
A = A(randperm(n),:);
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

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

Star Strider 2017년 7월 1일
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.

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

### 범주

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by