Print numbers on an array that have a unique row and column

조회 수: 2 (최근 30일)
Shawn Blancett
Shawn Blancett 2017년 9월 16일
댓글: Shawn Blancett 2017년 9월 16일
The code I wrote can print 1's on a unique column but can be on the same row. How could I get it to have a unique row?
for k=1:N % Loops N times
random = randi([1,N]); % Chooses a random number between 1 and board size
X(k,random) = 1; % Places a 'queen' on a random column
end

채택된 답변

Jan
Jan 2017년 9월 16일
편집: Jan 2017년 9월 16일
Perhaps you want:
index = randperm(8, 8);
X = zeros(8, 8);
for k = 1:8
X(k, index(k)) = 1;
end
0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0
0 0 0 0 1 0 0 0
1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 1 0 0 0 0 0
Alternatively without a loop:
X = zeros(8, 8);
X(sub2ind([8,8], 1:8, randperm(8, 8))) = 1

추가 답변 (2개)

Image Analyst
Image Analyst 2017년 9월 16일
Try this:
X = zeros(8, 8); % Initialize
rc = randi([1,8], 1, 2) % One location on the board.
X(rc(1), rc(2)) = 1 % Assign a queen to that square
  댓글 수: 7
Jan
Jan 2017년 9월 16일
I still don't get it: Do you mean a single 1 in each row and in each column?
Shawn Blancett
Shawn Blancett 2017년 9월 16일
If the board was NxN I want N amount of 1's the board, that have a unique row and column , so no 1 shares a column or row with another 1

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


Walter Roberson
Walter Roberson 2017년 9월 16일
X = zeros(N, N);
available = 1 : N;
for k=1:N % Loops N times
ridx = randi(length(available));
random = available(ridx);
available(ridx) = [];
X(k,random) = 1; % Places a 'queen' on a random column
end

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by