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
0 个评论
采纳的回答
Stephan
2020-11-24
k = 0:2;
coms = allcomb(k,k,k,k,k,k,k,k,k);
as expected there are 3^9 = 19683 results
更多回答(2 个)
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)
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!