How to get all possible arrays by randomizing in each cells with four items (1x6 array)

1 次查看(过去 30 天)
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.

采纳的回答

madhan ravi
madhan ravi 2018-12-29
编辑:madhan ravi 2018-12-29
Use random indexing by using randi if you want the elements to repeat or randperm if you don’t want the elements to be repeated
c=cell(1,4); % preallocate
syms x y z % define x y and z as you wish
a=[0,x,y,z];
for i =1:numel(c)
c{i}=a(randi(numel(a),1,6));
end
celldisp(c)
Note : 1 X 6 array means you want to fill each cell ( totally 4 cells) with 6 elements.
  4 个评论
madhan ravi
madhan ravi 2018-12-29
Yes your right , perhaps the OP wanted to just fill the cell arrays with those 4 elements since his quote "Yes Thank you so much... It works well." means he got what he was looking for .

请先登录,再进行评论。

更多回答(2 个)

Image Analyst
Image Analyst 2018-12-29
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.

Stephen23
Stephen23 2018-12-30
编辑:Stephen23 2018-12-30
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

类别

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