Print numbers on an array that have a unique row and column
Show older comments
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
Accepted Answer
More Answers (2)
Image Analyst
on 16 Sep 2017
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 Comments
Shawn Blancett
on 16 Sep 2017
Shawn Blancett
on 16 Sep 2017
Image Analyst
on 16 Sep 2017
It won't always be on the bottom row, but it will be on a unique, random row as requested. And in a single, unique random columns also. Is that not what you want? If not, what do you want?
Shawn Blancett
on 16 Sep 2017
Shawn Blancett
on 16 Sep 2017
Jan
on 16 Sep 2017
I still don't get it: Do you mean a single 1 in each row and in each column?
Shawn Blancett
on 16 Sep 2017
Walter Roberson
on 16 Sep 2017
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
Categories
Find more on Random Number Generation 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!