Possible combinations for a vector

3 次查看(过去 30 天)
Hi!
I have a vector s =[0,0,0,0,0,0,0,0,0] for which i wish to find out all possible combinations and also generate all possbile vectors for. A limit on each element to not be bigger than, lets say 2. So maximum would be like: s=[2,2,2,2,2,2,2,2,2]. Can someone helt me with this, please? Im going to use all the possible vectors for a plot where im going to plot all the vector values.
Best regards,
Daniel

采纳的回答

Stephan
Stephan 2020-11-24
You could use allcomb from FEX:
k = 0:2;
coms = allcomb(k,k,k,k,k,k,k,k,k);
as expected there are 3^9 = 19683 results

更多回答(2 个)

Rik
Rik 2020-11-24
编辑:Rik 2020-11-24
s=[0,0,0,0,0,0,0,0,0];
max_value_of_s=2;
num_combinations=(max_value_of_s+1)^numel(s);
disp(num_combinations)
19683
That is going to go up very quickly if you increase the max value.
Edit:
You can also generate the full array with this code:
N=9;
max_value_of_s=5;
% %naive method (this will cost extreme amounts of memory and processing time
% s=unique(nchoosek(repmat(1:max_value_of_s,1,N),N),'rows');
num_combinations=(max_value_of_s+1)^N;
s=zeros(num_combinations,N);
for row=2:num_combinations %leave row 1 as 0
s(row,:)=s(row-1,:);
s(row,1)=s(row,1)+1;%increment position 1
for col=1:(N-1)
if s(row,col)>max_value_of_s %overflow to the next 'digit'
s(row,col)=0;
s(row,col+1)=s(row,col+1)+1;
end
end
end
If you're curious, the naive approach results in this fairly quickly:
@Stephan, thank you for pointing this out, I had already found this when writing my edit, but I'll edit my original code as well.
  2 个评论
Daniel Arvidsson
Daniel Arvidsson 2020-11-24
Thanks, Rik! But, i would like to generate all those possible vectors, can you help me with that to?
Stephan
Stephan 2020-11-24
I think the max value is 3 - due to 0,1 and 2 can be elements.

请先登录,再进行评论。


Bruno Luong
Bruno Luong 2020-11-24
dec2base(0:3^9-1,3)-'0'

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by