How to get possible combinations of variables?

1 view (last 30 days)
Ajay Goyal
Ajay Goyal on 3 Feb 2016
Edited: Stephen23 on 3 Feb 2016
Dear Friends, I have got 20 vectors named (A1,A2...A20) with say 500 observations. I wanted to generate all possible combination. Moreover if A1A2 is a combination then it should also give values of A1*A2. Example,
A1 A2 A1A2
1 2 1*2
2 3 2*3
....
...
  1 Comment
Stephen23
Stephen23 on 3 Feb 2016
Edited: Stephen23 on 3 Feb 2016
Don't create twenty numbered variables. Although beginners keep doing this, using numbered variables leads to beginners writing slow, obfuscated, buggy programs. Here is why:
Note how the very first thing that Walter Roberson does in their comment (below) is to put all of these variables into one cell array, because this makes any processing of these variables much much easier. You should do the same: keep them in one variable, not twenty numbered ones.
The optimal storage would be in one numeric matrix.

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 3 Feb 2016
  2 Comments
Ajay Goyal
Ajay Goyal on 3 Feb 2016
Sorry It is not solving my purpose. All I want is a matrix with all possible combinations of given variables(A1...A20) with calculated values beneath them. Please guide me further with an example
Walter Roberson
Walter Roberson on 3 Feb 2016
You want to create variables A1A2, A1A3, and so on. And that is something you should avoid doing.
vars = {A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20};
nvars = length(vars);
results = cell(nvars, nvars);
for J = 1 : nvars - 1
results{J,J} = vars{K};
for K = J + 1 : nvars
t = vars{J}.*vars{K};
results{J,K} = t;
results{K,J} = t;
end
end
Now results{J,K} will be A_J .* A_K except that along the diagonal will be the original variables rather than the square of the variables.
Efficiency can be improved if the variables are known to be vectors, especially if their orientation is known ahead of time.

Sign in to comment.

Categories

Find more on Sequence and Numeric Feature Data Workflows in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!