Hi all,
I have a 1D array containing numbers from 1 to 5.
A = [1
2
3
4
5]
How can I find all possible combinations (without doubles), so that...
B = [1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
2
2 3
etc.]
I tried a number of combinators from the FEX but they don't give me the result I'm after.
Thanks!

1 Kommentar

KSSV
KSSV am 23 Feb. 2016
are you looking for something like the function perms?
doc perms

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Stephen23
Stephen23 am 23 Feb. 2016
Bearbeitet: Stephen23 am 23 Feb. 2016

1 Stimme

This will generate a cell array of all combinations of all possible lengths:
C = cell(size(A));
for k = 1:numel(C)
C{k} = nchoosek(A,k);
end
contained inside this cell array:
>> C{:}
ans =
1
2
3
4
5
ans =
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
ans =
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
ans =
1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5
ans =
1 2 3 4 5
Without padding they will not fit into one numeric array, as they have different number of columns. To pad them try this:
C = cell(size(A));
for k = 1:numel(C)
tmp = nchoosek(A,k);
C{k} = [tmp,NaN(size(tmp,1),numel(A)-k)];
end
N = cell2mat(C);
which creates this numeric array:
>> N
N =
1 NaN NaN NaN NaN
2 NaN NaN NaN NaN
3 NaN NaN NaN NaN
4 NaN NaN NaN NaN
5 NaN NaN NaN NaN
1 2 NaN NaN NaN
1 3 NaN NaN NaN
1 4 NaN NaN NaN
1 5 NaN NaN NaN
2 3 NaN NaN NaN
2 4 NaN NaN NaN
2 5 NaN NaN NaN
3 4 NaN NaN NaN
3 5 NaN NaN NaN
4 5 NaN NaN NaN
1 2 3 NaN NaN
1 2 4 NaN NaN
1 2 5 NaN NaN
1 3 4 NaN NaN
1 3 5 NaN NaN
1 4 5 NaN NaN
2 3 4 NaN NaN
2 3 5 NaN NaN
2 4 5 NaN NaN
3 4 5 NaN NaN
1 2 3 4 NaN
1 2 3 5 NaN
1 2 4 5 NaN
1 3 4 5 NaN
2 3 4 5 NaN
1 2 3 4 5

1 Kommentar

Barry
Barry am 23 Feb. 2016
Thank you very much, this is a great solution!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Jos (10584)
Jos (10584) am 23 Feb. 2016
Bearbeitet: Jos (10584) am 23 Feb. 2016

2 Stimmen

My function NCHOOSE will create those combinations without (slowly) looping over nchoosek. Each combination is stored in a cell. The cell array can be easily transformed into a 2D array by padding the entries with NaNs using PADCAT.
C = nchoose(1:5)
A = padcat(C{:})
NCHOOSE and PADCAT can be downloaded here:

3 Kommentare

Stephen23
Stephen23 am 23 Feb. 2016
+1 nice solution.
Barry
Barry am 26 Feb. 2016
+1 Thank you!
Barry
Barry am 26 Feb. 2016
I'm having trouble understanding what exactly the function "bitget" is doing, is there a way to see how this function is working using a for-loop? Thanks!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Descriptive Statistics finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 23 Feb. 2016

Kommentiert:

am 26 Feb. 2016

Community Treasure Hunt

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

Start Hunting!

Translated by