All combinations of a data set without mixing data across arrays

1 view (last 30 days)
Given the following data
Var1 = [1400, 1700, 1900]
Var2 = [1340, 1680, 1900, 1871, 789]
Var3 = [900]
Var4 = [950, 680]
Var5 = [100, 150, 150, 900]
I want to get all of the unique combinations of data without mixing between data sets i.e.
1400 1340 900 950 100
I am pretty new to MATLAB and am looking for a quick easy way to do this.

Answers (2)

Walter Roberson
Walter Roberson on 8 Aug 2023
Var1 = [1400, 1700, 1900];
Var2 = [1340, 1680, 1900, 1871, 789];
Var3 = [900];
Var4 = [950, 680];
Var5 = [100, 150, 150, 900];
[temp1{1:5}] = ndgrid(Var1, Var2, Var3, Var4, Var5);
temp2 = cellfun(@(m) m(:), temp1, 'Uniform', 0);
output = [temp2{:}];
size(output)
ans = 1×2
120 5
disp(output(1:15,:))
1400 1340 900 950 100 1700 1340 900 950 100 1900 1340 900 950 100 1400 1680 900 950 100 1700 1680 900 950 100 1900 1680 900 950 100 1400 1900 900 950 100 1700 1900 900 950 100 1900 1900 900 950 100 1400 1871 900 950 100 1700 1871 900 950 100 1900 1871 900 950 100 1400 789 900 950 100 1700 789 900 950 100 1900 789 900 950 100
You can see from the excerpt that output is working its way through all combinations, with the first column varying most quickly.

Bruno Luong
Bruno Luong on 8 Aug 2023
Edited: Bruno Luong on 9 Aug 2023
If you have R2023a use the stock combinations function
Var1 = [1400, 1700, 1900];
Var2 = [1340, 1680, 1900, 1871, 789];
Var3 = [900];
Var4 = [950, 680];
Var5 = [100, 150, 150, 900];
C = combinations(Var1, Var2, Var3, Var4, Var5)
C = 120×5 table
Var1 Var2 Var3 Var4 Var5 ____ ____ ____ ____ ____ 1400 1340 900 950 100 1400 1340 900 950 150 1400 1340 900 950 150 1400 1340 900 950 900 1400 1340 900 680 100 1400 1340 900 680 150 1400 1340 900 680 150 1400 1340 900 680 900 1400 1680 900 950 100 1400 1680 900 950 150 1400 1680 900 950 150 1400 1680 900 950 900 1400 1680 900 680 100 1400 1680 900 680 150 1400 1680 900 680 150 1400 1680 900 680 900
% if prefered array output instead of table
A = table2array(C)
ans = 120×5
1400 1340 900 950 100 1400 1340 900 950 150 1400 1340 900 950 150 1400 1340 900 950 900 1400 1340 900 680 100 1400 1340 900 680 150 1400 1340 900 680 150 1400 1340 900 680 900 1400 1680 900 950 100 1400 1680 900 950 150

Community Treasure Hunt

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

Start Hunting!