Info

This question is closed. Reopen it to edit or answer.

Pseuso random array with propery size 2 by 2 with integerd 1 to 6

4 views (last 30 days)
Hello. I want to create a pseudo random array of size 34*36 with intergers 1 to 6 which has a window property of 2 by 2 meaning that each 2 by 2 window in the array will be unique in the entire . Any help? Tnx
  1 Comment
Adam Danz
Adam Danz on 6 Dec 2019
I moved my answer to the comments section. After further inspection I've found 2x2 windows with duplicates. I figured out why but don't have time to now fix it....
--------------------------------------------------------------------
This solution uses randperm() which requires the Statistics and Machine Learning Toolbox. At the top you can define the size of your matrix, the maximum integer, and the size of your moving window.
The matrix m starts as all NaN values. It then moves the window along the rows and columns of your matrix and replaces any NaN values within the window with a random integer between 1 and nMax (6) that isn't already within the window.
This solution is also quite fast (0.03 sec).
m is the final matrix with random integer values between 1 and 6 without any repeats within a 2x2 window.
% Inputs
sz = [34, 36]; % size of matrix (nRows, nCol)
nMax = 6; % max integer
win = [2,2]; % window size (nRows, nCol)
% determine number of windows vertically and horzontally
nWin = sz - win + 1; % [vert, horz]
% Loop through horizontal windows
m = nan(sz); % initialize the matrix
vals = 1:nMax; % all possible integers
for i = 1:nWin(2)
% Loop through vertical windows
for j = 1:nWin(1)
% choose random integers for each NaN within the window
% but exclude integers that are already within the window.
winTemp = m(j:j+win(1)-1, i:i+win(2)-1); % Current window
valsTemp = vals(~ismember(vals,winTemp(:))); % Values that aren't already in window
winTemp(isnan(winTemp)) = valsTemp(randperm(numel(valsTemp),sum(isnan(winTemp(:))))); % replace NaNs
m(j:j+win(1)-1, i:i+win(2)-1) = winTemp; % add values to matrix
end
end

Answers (0)

This question is closed.

Community Treasure Hunt

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

Start Hunting!