Create array with random integers, skipping by a certain interval each time
4 次查看(过去 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!
0 个评论
回答(1 个)
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!