Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cs.utexas.edu!uunet!mcsun!ukc!stl!stc!root44!gwc From: gwc@root.co.uk (Geoff Clare) Newsgroups: comp.unix.questions Subject: Re: matrix invert routine Summary: transpose, not rotate Message-ID: <1046@root44.co.uk> Date: 17 Nov 89 13:09:21 GMT References: <1612@xn.LL.MIT.EDU> <2560@ucsfcca.ucsf.edu> <4573@emory.mathcs.emory.edu> Reply-To: gwc@root.co.uk (Geoff Clare) Organization: UniSoft Ltd, London, England Lines: 53 Followup-To: In article <4573@emory.mathcs.emory.edu> arnold@emory.UUCP (Arnold D. Robbins {EUCC}) writes: >>In article <1612@xn.LL.MIT.EDU>, rkc@XN.LL.MIT.EDU (rkc) writes: >>> [ request for matrix transposing utility ] > >In article <2560@ucsfcca.ucsf.edu> root@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@root.co.uk (Dumb mailers: ...!uunet!root.co.uk!gwc) Tel: +44-1-315-6600