# Create 9x9 matrix with RANDI between [0,2] with each 0,1, and 2 repeating three times each per column.

57 views (last 30 days)
Ryan Graham on 23 Sep 2020 at 20:50
Edited: Abdolkarim Mohammadi-Balani on 23 Sep 2020 at 22:02
I'm trying to create a 9x9 matrix with random number generation from 0 to 2 using RANDI:
X = randi([0,2], 9,9)
However, I want to force each of the 9 columns to show an equal distribution of 0's, 1's, and 2's (3 x of each number per column). I'm having difficulty finding a loop that can do this. Any help would be great (very new to this type of MATLAB work).
Thanks.

Abdolkarim Mohammadi-Balani on 23 Sep 2020 at 20:59
Edited: Abdolkarim Mohammadi-Balani on 23 Sep 2020 at 21:03
You can first create a vector with the values you need:
Reference = repelem (0:2,3)';
Then you initialize the 9x9 matrix with zeros(), and finally fill in the columns with random permutations of Reference using randperm().

Abdolkarim Mohammadi-Balani on 23 Sep 2020 at 21:42
Reference = repelem (0:2,3)';
M = zeros (9);
for i1 = 1:9
M (:,i1) = Reference (randperm(9));
end
Ryan Graham on 23 Sep 2020 at 21:50
Excellent, thank you very much for your help, this works and is a nice guide for me going forward. For future reference, if the Matrix is no longer a square, I should be able to just change the M= zeros (9) to a different number of rows and columns?
Abdolkarim Mohammadi-Balani on 23 Sep 2020 at 21:59
Yes. But the number of rows should not change. For example: zeros (9,4). Otherwise, you should update Reference have the same number of elements as the number of rows in M.

Bruno Luong on 23 Sep 2020 at 21:25
Edited: Bruno Luong on 23 Sep 2020 at 21:26
[~,A] = sort(rand(9)); A = mod(A,3)