Possible combinations for a vector

3 Ansichten (letzte 30 Tage)
Daniel Arvidsson
Daniel Arvidsson am 24 Nov. 2020
Beantwortet: Bruno Luong am 24 Nov. 2020
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

Akzeptierte Antwort

Stephan
Stephan am 24 Nov. 2020
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

Weitere Antworten (2)

Rik
Rik am 24 Nov. 2020
Bearbeitet: Rik am 24 Nov. 2020
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 Kommentare
Daniel Arvidsson
Daniel Arvidsson am 24 Nov. 2020
Thanks, Rik! But, i would like to generate all those possible vectors, can you help me with that to?
Stephan
Stephan am 24 Nov. 2020
I think the max value is 3 - due to 0,1 and 2 can be elements.

Melden Sie sich an, um zu kommentieren.


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

Kategorien

Mehr zu Mathematics finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by