4
$\begingroup$

I have two separate lists, say:

L1={{1,2},{1,3},{2,3}}
L2={A12,A13,A23}

How can I construct a single matrix A with values $$\left(\begin{array}{ccc} 0 & A12 & A13 \\ 0 & 0 & A23 \\ 0 & 0 & 0 \end{array}\right) $$

I understand that one can do loop:

A=ConstArray[0,{3,3}];
For[i=1, i<= Length @ L1, i++,
    A[[L1[[i,1]],L1[[i,2]]] = L2[[i]]
    ]

Still, this construction does not seem general, especially if working with multidimensional (multiply nested) lists. Is there a way to formalise this algorithm? Furthermore, I am using "For" loop which is not very natural for Mathematica.

$\endgroup$
6
$\begingroup$

The following approach should be pretty general:

Normal @ SparseArray[L1 -> L2, {3, 3}, 0]

(* Out: {{0, A12, A13}, {0, 0, A23}, {0, 0, 0}} *)
$\endgroup$
1
  • $\begingroup$ Thank you! That is exactly what I was looking for! $\endgroup$ – Sergei Ovchinnikov Feb 10 '20 at 21:36

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.