6
$\begingroup$

I have two lists as:

abs = {a1, a2, a3, a4};
trs = {t1, t2, t3, t4};

I like to build the following special matrix:

mat = {
   {    0, a2 t1, a3 t1, a4 t1},
   {a1 t2,     0, a3 t2, a4 t2},
   {a1 t3, a2 t3,     0, a4 t3},
   {a1 t4, a2 t4, a3 t4,     0}
   };

It is easy to create this matrix $mat$ by several matrix operations. However, I like to obtain $mat$ in a very compact Mathematica code. In fact, a Mathematica Function such as F[abs_,trs_]:= is very much desirable as I will use it in many occasions.

$\endgroup$
  • 2
    $\begingroup$ I assume the a3 t3 term should be a3 t4 $\endgroup$ – mikado Oct 2 '18 at 18:34
  • $\begingroup$ @Mikado: You are perfectly right. The term $a3 t3$ should have been "a3 t4". Thank you for precision. $\endgroup$ – Tugrul Temel Oct 2 '18 at 19:49
8
$\begingroup$
F[abs_, trs_] := ReplacePart[KroneckerProduct[trs, abs], {k_, k_} -> 0]

F[{a1, a2, a3, a4}, {t1, t2, t3, t4}] // MatrixForm

$\left( \begin{array}{cccc} 0 & \text{a2} \text{t1} & \text{a3} \text{t1} & \text{a4} \text{t1} \\ \text{a1} \text{t2} & 0 & \text{a3} \text{t2} & \text{a4} \text{t2} \\ \text{a1} \text{t3} & \text{a2} \text{t3} & 0 & \text{a4} \text{t3} \\ \text{a1} \text{t4} & \text{a2} \text{t4} & \text{a3} \text{t4} & 0 \end{array} \right)$

$\endgroup$
  • $\begingroup$ @GravityGuy: very nice construct... $\endgroup$ – Tugrul Temel Oct 2 '18 at 18:22
  • 5
    $\begingroup$ Also: (# - DiagonalMatrix[Diagonal[#]]) & [KroneckerProduct[trs, abs]] $\endgroup$ – J. M.'s technical difficulties Oct 2 '18 at 18:23
  • 1
    $\begingroup$ Yeah, the latter should be faster for large matrices... $\endgroup$ – Henrik Schumacher Oct 2 '18 at 18:59
  • 2
    $\begingroup$ @Terbernus I meant J.M.'s proposal. In my experience, ReplacePart is seldomly a part of an efficient solution. $\endgroup$ – Henrik Schumacher Oct 2 '18 at 19:54
  • 1
    $\begingroup$ @Tebernus I almost don't dare to ask: Do you use symbolic list? $\endgroup$ – Henrik Schumacher Oct 2 '18 at 21:00
8
$\begingroup$

Two other alternatives

Outer[Times, trs, abs] - DiagonalMatrix[abs*trs]

Transpose[{trs}].{abs} - DiagonalMatrix[abs*trs]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.