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

2 views (last 30 days)
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?

Answers (1)

Adam Danz
Adam Danz on 8 Apr 2022
Edited: Adam Danz on 8 Apr 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

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!