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

추가 답변 (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에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by