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

3 ビュー (過去 30 日間)
Blake Seaton
Blake Seaton 2020 年 7 月 7 日
編集済み: Blake Seaton 2020 年 7 月 7 日
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 Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by