9
$\begingroup$

How to create a SparseArray without using lists of rule in MMA?

In MMA we can define a SparseArray using lists of rule

s = SparseArray[{{1, 1} -> 1, {2, 2} -> 2, {3, 3} -> 3, {1, 3} -> 4}]

Is it possible that we can create SparseArray using vectors input?

E.g.:

u1 = {1, 2, 3, 1};    
v1 = {1, 2, 3, 3};    
w1 = {1, 2, 3, 4};

s = SparseArray[u1,v1,w1,...]
$\endgroup$

2 Answers 2

11
$\begingroup$

SparseArray also supports

SparseArray[positions -> values]

So on the example:

SparseArray[Transpose@{u1, v1} -> w1]
$\endgroup$
7
$\begingroup$

A one liner

s = Rule @@@ Transpose@{Transpose@{u1, v1}, w1} // SparseArray

Check

s // MatrixForm

$$\left( \begin{array}{ccc} 1 & 0 & 4 \\ 0 & 2 & 0 \\ 0 & 0 & 3 \\ \end{array} \right)$$

$\endgroup$
2
  • $\begingroup$ Nice! thanks a lot! $\endgroup$
    – ABCDEMMM
    Dec 31, 2021 at 2:31
  • 1
    $\begingroup$ Also (s = SparseArray[{#[[1]], #[[2]]} -> #[[3]] & /@ Transpose[{u1, v1, w1}]]) // MatrixForm $\endgroup$
    – Bob Hanlon
    Dec 31, 2021 at 3:04

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.