Want my random matrix to only display distinct elements

1 view (last 30 days)
Current'y running this code to output a random 5x5 matrix with elements between 1 & n^2, n being 5 in this case (array size). I want every element to be a DISTINCT integer between 1-25 a.k.a. non-repeating. What must I adjust?
randomMatrix(5)
function A=randomMatrix(n)
A=zeros(n);
for i=1:n
for j=1:n
A(i,j)=uint16(rand(1)*(n^2-1)+1);
end
end
end
OUTPUT:
21 23 4 23 16
3 8 14 24 24
5 24 24 13 20
4 11 23 20 24
17 2 21 23 17

Answers (1)

DGM
DGM on 16 Feb 2022
Edited: DGM on 16 Feb 2022
Just like so
N = 5;
A = 1:N^2;
A = reshape(A(randperm(N^2)),N,N)
A = 5×5
20 12 10 16 21 25 6 7 18 17 13 8 3 2 23 14 1 19 5 24 15 22 4 11 9
If you want to cast the output as integer class, you can.

Categories

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

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!