1

I have a range of conditions I want to run through a Matlab code,

Var1 = {'A1', 'B1'};
Var2 = {'A2', 'B2', 'C2', 'D2'};
Var3 = {2.5, 3, 3.5, 4, 4.5};
Var4 = {2E-6, 5E-6, 10E-6, 0.25E-3, 0.5E-3, 1E-3, 2E-3};
Var5 = {5, 10, 15, 20, 25, 30, 40, 50, 60, 70, 80, 90, 100, 125, 150, 200};

Is there an easy way I can create a matrix (or cell array) that has all the 2*4*5*7*16 combinations?

user1543042
  • 3,422
  • 1
  • 17
  • 31

1 Answers1

1

The result needs to be a cell array, because a matrix can't contain numbers and strings simultaneously.

This question and its answers achieve what you want but with vector inputs (as opposed to cell array inputs). So you can

  1. Transform each of your input variables into a numeric vector, to be used as index;
  2. Generate all combinations;
  3. Convert back by indexing.

Code:

%// Step 1:
vectors = {1:numel(Var1), 1:numel(Var2), 1:numel(Var3), 1:numel(Var4), 1:numel(Var5)};
%// Step 2:
n = numel(vectors);
combs = cell(1,n);
[combs{end:-1:1}] = ndgrid(vectors{end:-1:1});
combs = cat(n+1, combs{:});
combs = reshape(combs,[],n);
%// Step 3:
result = [Var1(combs(:,1)).' Var2(combs(:,2)).' Var3(combs(:,3)).' ...
    Var4(combs(:,4)).' Var5(combs(:,5)).'];

In your example, this produces the following 4480x5 cell array:

result = 
    'A1'    'A2'    [2.5000]    [2.0000e-006]    [  5]
    'A1'    'A2'    [2.5000]    [2.0000e-006]    [ 10]
    'A1'    'A2'    [2.5000]    [2.0000e-006]    [ 15]
        ...
    'B1'    'D2'    [4.5000]    [     0.0020]    [150]
    'B1'    'D2'    [4.5000]    [     0.0020]    [200]
Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147