matrix invert routine

Geoff Clare gwc at root.co.uk
Sat Nov 18 00:09:21 AEST 1989


In article <4573 at emory.mathcs.emory.edu> arnold at emory.UUCP (Arnold D. Robbins {EUCC}) writes:
>>In article <1612 at xn.LL.MIT.EDU>, rkc at XN.LL.MIT.EDU (rkc) writes:
>>> [ request for matrix transposing utility ]
>
>In article <2560 at ucsfcca.ucsf.edu> root at cca.ucsf.edu (Systems Staff) writes:
>>the transpose with standard Unix tools (I would look at awk first) ....
>
>Aha! No sooner said than done.  From the 2.11 gawk.texinfo manual:
>
>	awk '{
>	     if (max_nf < NF)
>	          max_nf = NF
>	     max_nr = NR
>	     for (x = 1; x <= NF; x++)
>	          vector[x, NR] = $x
>	}
>	
>	END {
>	     for (x = 1; x <= max_nf; x++) {
>	          for (y = max_nr; y >= 1; --y)
>	               printf("%s ", vector[x, y])
>	          printf("\n")
>	     }
>	}'

There are a number of problems with this answer.  Firstly the request
was for a program to *transpose* a matrix, not *rotate* it.  Secondly I
wouldn't call gawk a "standard" UNIX tool, however the program can
easily be made portable to all versions of awk by replacing vector[a, b]
with vector[a "," b] as necessary.  Thirdly the two dimensional array is
actually unnecessary and slows the execution down considerably.  A more
efficient method is to build the rows of the new matrix on the fly.

Putting all this together, here is my solution for a matrix transposing
utility using (portable) awk.

exec awk '{
	if (NF > n)
		n = NF
	for (i = 1; i <= NF; i++)
		row[i] = row[i] " " $i
}
END {
	for (i = 1; i <= n; i++)
		print row[i]
}' ${1+"$@"}

A modification so that it doesn't put an extra space character on the
front of each line is left as an exercise for the reader.

-- 
Geoff Clare, UniSoft Limited, Saunderson House, Hayne Street, London EC1A 9HH
gwc at root.co.uk  (Dumb mailers: ...!uunet!root.co.uk!gwc)  Tel: +44-1-315-6600



More information about the Comp.unix.questions mailing list