How to get possible combinations of variables?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Stephen23
el 3 de Feb. de 2016
Editada: Stephen23
el 3 de Feb. de 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.
Respuestas (1)
Walter Roberson
el 3 de Feb. de 2016
2 comentarios
Walter Roberson
el 3 de Feb. de 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.
Ver también
Categorías
Más información sobre Sequence and Numeric Feature Data Workflows en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!