Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: VectorToMatrix
Replies: 6   Last Post: Jul 8, 1996 2:19 AM

 Messages: [ Previous | Next ]
 Paul Abbott Posts: 1,437 Registered: 12/7/04
Re: VectorToMatrix
Posted: Jul 8, 1996 2:19 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.)

See The Mathematica Journal 4(1):34. That example converts a vector
into a symmetric matrix. It is easy to modify this example to meet

To convert a vector into a symmetric matrix, note that an m x m
symmetric matrix corresponds to a vector of length m(m+1)/2 (a so-
called traingular number). Inverting this formula:

In[1]:= dim[n_] = (m /. Solve[m(m+1)/2 == n, m] // Last)

Out[1]= -1 + Sqrt[1 + 8 n]
------------------
2

In[2]:= vec = {a,b,c,d,e,f,g,h,i,j};

In[3]:= dim[Length[vec]]

Out[3]= 4

This is fast so you might as well compute it.

In[4]:= VectorToMatrix[vec_ /; IntegerQ[dim[Length[vec]]]] :=
Module[{m = dim[Length[vec]],i,j},
Table[If[i>=j,0,vec[[j + (i-1)(m-i/2)-1]]],
{i, m}, {j, m+1} ]]

In[5]:= VectorToMatrix[vec] // MatrixForm

Out[17]//MatrixForm=
0 a b c d

0 0 e f g

0 0 0 h i

0 0 0 0 j

Cheers,
Paul
_________________________________________________________________
Paul Abbott
Department of Physics Phone: +61-9-380-2734
The University of Western Australia Fax: +61-9-380-1014
Nedlands WA 6907 paul@physics.uwa.edu.au
AUSTRALIA http://www.pd.uwa.edu.au/Paul
_________________________________________________________________

Date Subject Author
6/26/96 Robert Pratt
6/28/96 Demetri Mouratis
6/28/96 Dr. T. L. Marchioro II
7/8/96 Paul A. Rubin
7/8/96 Count Dracula
7/8/96 Nicholas Santucci
7/8/96 Paul Abbott