Create array with random integers, skipping by a certain interval each time

3 次查看(过去 30 天)
Hi,
I would like help writing a piece of code that will create a 1 x n array, of which each number is a random integer within a user-defined range (magic_number), but after each number, the range is shifted by an interval equal to magic_number. I also want the total size of the array to equal magic_number.
For example:
magic_number = 10;
resulting_array = [randi(magic_number) ...
(randi(magic_number) + magic_number) ...
(randi(magic_number) + 2*magic_number) ...
(randi(magic_number) + 3*magic_number) ...
(randi(magic_number) + 4*magic_number) ...
(randi(magic_number) + 5*magic_number) ...
(randi(magic_number) + 6*magic_number) ...
(randi(magic_number) + 7*magic_number) ...
(randi(magic_number) + 8*magic_number) ...
(randi(magic_number) + 9*magic_number)];
resulting_array
One possible answer for resulting_array would thus be: 4 16 23 39 41 60 67 79 88 100
The above code does almost what I'm looking for, but I want it to be fully automated. Changing magic_number will change the random integer range and the interval shift, but not the total size of the array. For example, if magic_number was changed to 9, I would have to delete the last line. If it was changed to 11, I would have to add a line, etc.
I considered randperm, but as far as I know there is no way to specify jumping intervals like this with randperm. I also considered the use of a for loop, but I couldn't quite get there.
Any help is greatly appreciated!

回答(1 个)

Michael Soskind
Michael Soskind 2020-7-7
Hi Blake,
Using a for loop, your code could look as follows:
for i = 1:magic_number % iterate for the number of items in resulting_array
% add a random number up to magic number, and add n-1*randi
resulting_array(i) = randi(magic_number) + (i-1)*randi(magic_number);
end
This should yield what you are looking for, and hope that helps
Michael
  1 个评论
Blake Seaton
Blake Seaton 2020-7-7
编辑:Blake Seaton 2020-7-7
Hi Michael, your code was just a bit off (want the added interval to be the same each time, not random), but it got me to the correct answer:
for i = 1:magic_number
resulting_array(i) = randi(magic_number) + (i-1)*(magic_number);
end
Thank you!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by