Possible combinations for a vector

1 回表示 (過去 30 日間)
Daniel Arvidsson
Daniel Arvidsson 2020 年 11 月 24 日
回答済み: Bruno Luong 2020 年 11 月 24 日
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
  1 件のコメント
Daniel Arvidsson
Daniel Arvidsson 2020 年 11 月 24 日
Thanks alot, Stephan!

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by