All combinations of matrix elements?

Hello,
I'd like to find all combinations of 2 elements in a matrix.
For example, a = [1:4; 5:8; 9:12]', the result should be [1*1 1*2 1*3 1*4 1*5 ... 1*12 2*2 2*3 ... 2*12 3*3 ... 12*11 12*12]';
Thanks for your help!

 採用された回答

Stephen23
Stephen23 2016 年 9 月 23 日
編集済み: Stephen23 2016 年 9 月 27 日

2 投票

Method One: matrix multiply and tril:
You can use a simple matrix multiply to do this:
>> z = a(:) * a(:)'
and use tril to get the triangular lower portion:
>> z(tril(true(size(z))))
Method Two: FEX submission combinator:
>> prod(a(combinator(numel(a),2,'c','r')),2)

5 件のコメント

Xiaohan Du
Xiaohan Du 2016 年 9 月 23 日
Hi Stephen,
This is awesome! Thanks!
What if a is made of row vectors of the same length rather than constants? For example, a = [a1 a2 a3; a4 a5 a6]', where a1-a6 are 3 by 1 column vectors.
Stephen23
Stephen23 2016 年 9 月 23 日
@Xiaohan Du: can you please post a numeric example for your last question.
Xiaohan Du
Xiaohan Du 2016 年 9 月 26 日
編集済み: Xiaohan Du 2016 年 9 月 26 日
@Stephen a numerical example:
var = rand(20, 3);
no = 5;
numcell = mat2cell(var, size(var, 1)/no*ones(1, no), ones(1, 3));
result in a 5 by 3 cell 'numcell' which contains 4 by 1 double for each cell.
Now for numcell, I'd like the same effort as
z = numcell(:) * numcell(:)';
But MATLAB gives me error: Undefined operator '*' for input arguments of type 'cell'.
Stephen23
Stephen23 2016 年 9 月 26 日
@Xiaohan Du: cell arrays are containers for other data classes. They cannot have mathematical operations applied to them. Whatever you want to do (it is not clear to me) needs to be applied to a numeric array, not a cell array.
James Tursa
James Tursa 2016 年 9 月 26 日
@Xiaohan Du: It is unclear what solution you really want from your original post. Stephen's answer does the entire outer product, which does not match your example result which appears to be only one triangular portion of the outer product. Andrei's answer does this triangular portion which matches your original post example result. What is it you really want? (The accepted answer does not match the question example result)

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

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2016 年 9 月 23 日
編集済み: Andrei Bobrov 2016 年 9 月 23 日

2 投票

b = a(:)*a(:).';
out = b(tril(true(size(b))));

カテゴリ

ヘルプ センター および File ExchangeOperators and Elementary Operations についてさらに検索

質問済み:

2016 年 9 月 23 日

編集済み:

2016 年 9 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by