This tip comes care of Dr. Michael Monagan at Simon Fraser University. Represent your sparse matrix as a list of rows, and represent each row as a linear equation in an indexed name. For example:

A := [[1,0,3],[2,0,0],[0,4,5]];

S := [ 1*x[1] + 3*x[3], 2*x[1], 4*x[2]+5*x[3] ];

To compute the product of the matrix A with a Vector X, assign x[i] := V[i] and evaluate. This can be done inside of a procedure because x is a table.

V := [7,8,9]: for i to 3 do x[i] := V[i] end do: eval(S); # result

for i to 3 do x[i] := evaln(x[i]) end do: # unassign

Don't forget to unassign. Note that this method of assignment is slow when V is a big list. In short, we need to use "for i in V", which does one nice linear pass through V. This is what I do:

n := 0; count := proc() global n; n := n+1 end proc:

for i in V do x[count()] := i end do: eval(S);

for i to 3 do x[i] := evaln(x[i]) od:

In a real procedure, n would be lexically scoped and not a global variable. Instead of an explicit loop you can also use seq and assign.

n := 0; count := proc() global n; n := n+1 end proc:

seq(assign(x[count()],i), i=V);

eval(S);

seq(unassign('x[i]'), i=1..3);

Of course, where this trick really shines is in doing back substitution. You can easily substitute tens of thousands of variables into any number of equations, all in linear time.


Please Wait...