How to get all possible arrays by randomizing in each cells with four items (1x6 array)
Show older comments
Hi! I would like to know all possible arrays for 1x6 vector. Each cells may be 0 (or) x (or) y (or) z. Some can be repeated and some may exclude in an array.
Some of the results should be like below:
[x,y,x,0,z]; [x,x,x,x,z]; [y,0,0,0,0,z]; [z,0,y,0,0,x];......
Thank you so much.
Accepted Answer
More Answers (2)
Image Analyst
on 29 Dec 2018
At first I though of using perms() on your list of numbers but since that doesn't allow more output numbers than input numbers (6 output with only 4 input), I thought that a 6-nested for loop would work. This code figures out all possible permutations of the 4 variables taken 6 per draw. You will of course have 4^6 possible unique combinations.
tic
x = 99;
y = 188;
z = 277; % Whatever numbers you want...
listOfNumbers = [0, x, y, z]
c = zeros(4^6, 6); % Preallocate
% Generate all possible combinations.
row = 1;
for k1 = 1 : length(listOfNumbers)
for k2 = 1 : length(listOfNumbers)
for k3 = 1 : length(listOfNumbers)
for k4 = 1 : length(listOfNumbers)
for k5 = 1 : length(listOfNumbers)
for k6 = 1 : length(listOfNumbers)
c(row, :) = [listOfNumbers(k1), ...
listOfNumbers(k2), ...
listOfNumbers(k3), ...
listOfNumbers(k4), ...
listOfNumbers(k5), ...
listOfNumbers(k6)];
row = row + 1;
end
end
end
end
end
end
toc
Time to run is a speedy 0.001 seconds (a millsecond), so don't be afraid of the for loops.
2 Comments
San May
on 29 Dec 2018
madhan ravi
on 29 Dec 2018
Edited: madhan ravi
on 29 Dec 2018
+1 @sir Image Analyst , always precise!
A simple solution with ndgrid:
>> x = 99;
>> y = 188;
>> z = 277;
>> C = cell(1,6);
>> [C{:}] = ndgrid([0,x,y,z]);
>> C = cellfun(@(a)a(:),C,'uni',0);
>> M = [C{:}]
M =
0 0 0 0 0 0
99 0 0 0 0 0
188 0 0 0 0 0
277 0 0 0 0 0
0 99 0 0 0 0
99 99 0 0 0 0
188 99 0 0 0 0
277 99 0 0 0 0
0 188 0 0 0 0
99 188 0 0 0 0
... lots of lines here
99 99 277 277 277 277
188 99 277 277 277 277
277 99 277 277 277 277
0 188 277 277 277 277
99 188 277 277 277 277
188 188 277 277 277 277
277 188 277 277 277 277
0 277 277 277 277 277
99 277 277 277 277 277
188 277 277 277 277 277
277 277 277 277 277 277
>> size(M)
ans =
4096 6
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!