How to get possible combinations of variables?

3 ビュー (過去 30 日間)
Ajay Goyal
Ajay Goyal 2016 年 2 月 3 日
編集済み: Stephen23 2016 年 2 月 3 日
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
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
Walter Roberson 2016 年 2 月 3 日
  2 件のコメント
Ajay Goyal
Ajay Goyal 2016 年 2 月 3 日
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 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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by