How to get possible combinations of variables?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2016-2-3
编辑:Stephen23
2016-2-3
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.
回答(1 个)
Walter Roberson
2016-2-3
2 个评论
Walter Roberson
2016-2-3
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!