Assign a number of random elements to different variables?
3 views (last 30 days)
Show older comments
How can I assign integers from 1 to 40 randomly to six different variables such that they don't repeat in any of the arrays and no number gets left out?
The array size of each variable should be random as well.
An approach I have considered is using
v = randperm(40);
a = randi([1,40])
Sat1 = v(1:a)
b = randi([a,40])
Sat2 = v(a+1:b)
c = randi([b,40])
Sat3 = v(b+1:c)
d = randi([c,40])
Sat4 = v(c+1:d)
e = randi([d,40])
Sat5 = v(d+1:e)
f = randi([e,40])
Sat6 = v(e+1:f)
But then the problem is in some generations will lead to empty arrays or even unassigned integers! Any ideas?
0 Comments
Accepted Answer
David Hill
on 4 Jun 2020
v=randperm(40);
k=[];
while isempty(k)
a=randi(40,1000,6);%you could change 40 to something smaller if you want to limit the maximum
b=sum(a,2);
k=a(b==40,:);
end
k=k(1,:);
c=1;
for m=1:6
Sat{m}=v(c:c+k(m)-1);
c=c+k(m);
end
6 Comments
More Answers (1)
Stephen23
on 4 Jun 2020
Using one cell array is much better than having lots of separate variables, so that is what this answer does.
>> v = randperm(40); % random values
>> x = randi(6,1,40); % random indices
Method one: accumarray:
>> c = accumarray(x(:),v(:),[],@(a){a(:).'});
checking:
>> c{:}
ans =
17 28 36 1
ans =
35 9 20 37 24 4 21 23 33
ans =
3 14 6 5 40 32 13 12
ans =
29 31 38 10 15 16
ans =
34 27 7 25 30 18 11 22
ans =
8 19 26 2 39
Method two: arrayfun:
>> c = arrayfun(@(n)v(x==n),1:6,'uni',0);
checking:
>> c{:}
ans =
28 17 1 36
ans =
35 33 21 37 23 4 24 9 20
ans =
32 40 6 3 14 5 13 12
ans =
16 38 29 31 15 10
ans =
22 34 11 30 7 25 27 18
ans =
8 26 19 2 39
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!