
Re: VectorToMatrix
Posted:
Jun 28, 1996 10:00 AM


Robert Pratt wrote: > I want to define a function VectorToMatrix[list_, n_] that behaves as > follows: > > VectorToMatrix[{a,b,c,d,e,f,g,h,i,j}, 4]//MatrixForm > > 0 a b c d > 0 0 e f g > 0 0 0 h i > 0 0 0 0 j > > Now n can be determined from Length[list], which will always be equal to > n choose 2 for some n. But I would rather input n to save that > computation. (I will be doing this for a lot of vectors.) > > Any ideas?
This proved a little more difficult than I had thought... but I think the following is what you want to convert a vector into the elements of an upper triangular matrix. I am a little surprised your example is not nXn, but assume that is what you want. If not, the following should be easy to adapt. No doubt some guru can present a more efficient method :)
vectorToUTMatrix[l_List, n_Integer]:= Module[{temp, temp1}, (*make the first row *) temp=RotateRight[Join[l, Table[0, {n}]]]; temp1=Take[temp, n+1];
(* now form other rows and join them to first *) Do[( temp=Drop[temp, {iter+1, n+1}]; temp=RotateRight[temp]; temp1=Join[temp1, Take[temp, n+1]];), {iter, 1, n1}]; (* Partition list of elements into matrix of proper shape *) Partition[temp1,n+1] ]
For me this yields:
l={a, b, c, d, e, f, g, h, i, j};
vectorToUTMatrix[l,4]//MatrixForm
0 a b c d
0 0 e f g
0 0 0 h i
0 0 0 0 j
l=Join[l, {k, el, m, n, o}];
vectorToUTMatrix[l,5]//MatrixForm
0 a b c d e
0 0 f g h i
0 0 0 j k el
0 0 0 0 m n
0 0 0 0 0 o
l=Join[l, {p,q, r, s, t, u}];
vectorToUTMatrix[l,6]//MatrixForm
0 a b c d e f
0 0 g h i j k
0 0 0 el m n o
0 0 0 0 p q r
0 0 0 0 0 s t
0 0 0 0 0 0 u
etc. I hope this is what you were after.
TLM
 Dr. Thomas L. Marchioro II Twowheeled theoretical physicist Applied Mathematical Sciences 5152949779 Ames Laboratory 5154329142 (home) Ames, Iowa 50011 tlm@ameslab.gov Project Coordinator: Undergraduate Computational Engineering and Sciences http://uces.ameslab.gov/

