Beginner coding; my second, simpler approach at trying to make all elements distinct.

9 vues (au cours des 30 derniers jours)
So this is what I've come up with on my own to print a 3x3 random matrix of integers only; no element value exceeding n^2 (9 in this case). I think I've done that correctly, it seems to be working. Keep in mind I've just started learning.
what can I add to ensure that every element will be unique, i.e for this case, all numbers 1-9 should be represented ONCE in the 3x3 matrix; none repeating. As you can see from what I've pasted from the command window, there are two 8's!
If you're willing please explain the thought behind it and exactly how I should approach modifying what's existing. Thanks!
Script
___________
n=3
q=(n^2)*rand(n)
ceil(q)
__________
OUTPUT:
n =
3
q =
7.3798 4.7820 5.4986
6.4652 2.9263 7.0092
8.7178 0.9507 3.8111
ans =
8 5 6
7 3 8
9 1 4

Réponses (1)

James Tursa
James Tursa le 16 Fév 2022
FYI, to generate random integers you can use the randi( ) function instead of ceil(value*rand( )):
To get unique integers you can use the randperm( ) function. E.g.,
randperm(n^2)
That will get you a vector. To get a matrix simply reshape the result:
reshape(randperm(n^2),n,n)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by