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

2 次查看(过去 30 天)
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?

回答(1 个)

Adam Danz
Adam Danz 2022-4-8
编辑:Adam Danz 2022-4-8
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

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by