Is there a way to set the range of values when using the magic function?

2 vues (au cours des 30 derniers jours)
Ryan O Malley
Ryan O Malley le 8 Avr 2022
Modifié(e) : Adam Danz le 8 Avr 2022
Lets say I have
M=magic(5)
The values randomly assigned to each positon in the matrix will range from 1 to 25.
Is there any way to generate a 5x5 matrix like this but to control the range of each element, for example 1 to 6?

Réponses (1)

Adam Danz
Adam Danz le 8 Avr 2022
Modifié(e) : Adam Danz le 8 Avr 2022
The values returned by magic(n) are not randomly assigned (see documentation).
I think what you're describing is randperm.
n = reshape(randperm(25),5,5) % values 1:25
n = 5×5
10 8 6 20 18 15 4 17 21 16 14 7 9 12 22 1 25 13 2 23 19 3 5 24 11
or perhaps randi for sampling with replacement
n = randi(6,5,5) % values 1:6
n = 5×5
1 1 6 4 2 3 6 2 4 5 2 2 5 4 1 3 3 4 2 6 1 1 3 6 4

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by