#!/usr/local/bin/perl # M2A.p reads in a sparse matlab matrix like RAM17.5 # and spits out an alist. # usage # M2A.p RAM17.5 > ram17.5 # $N=0;$M=0; eval "\$$1=\$2" while @ARGV && $ARGV[0]=~ /^([\w\[\]]+)=(.*)/ && shift ; print STDERR "--------M2A.p----------- DJCM Wed 17/4/02\n" ; # first, read the old list in while(<>) { if ( /\((\d+)\,(\d+)\)/ ) { $m=$1;$n=$2; &mnadd($m,$n); if($n>$N){$N=$n;} if($m>$M){$M=$m;} } else { print STDERR "unreadable line:\n$_"; } } # print STDERR "done N = $N ; M = $M\n" ; if ( 1 ) { $head = "$N $M\n" ; print STDERR "Writing code.\n" ; # find $t (max) and $tr (max) $t = 0 ; $tr = 0 ; for ( $n = 1 ; $n <= $N ; $n ++ ) { if ( $numnlist[$n] > $t ) { $t = $numnlist[$n] ; } } for ( $m = 1 ; $m <= $M ; $m ++ ) { if ( $nummlist[$m] > $tr ) { $tr = $nummlist[$m] ; } } $head .= "$t $tr\n" ; # append zeros to short lines for ( $n = 1 ; $n <= $N ; $n ++ ) { $thisn = $numnlist[$n] ; if ( $thisn ) { $head .= "$thisn " ; while ( $thisn < $t ) { $nlist[$n] .= "0\t" ; $thisn ++ ; } } # otherwise it is a dead column } $head .= "\n" ; for ( $m = 1 ; $m <= $M ; $m ++ ) { $thism = $nummlist[$m] ; $head .= "$thism " ; while ( $thism < $tr ) { $mlist[$m] .= "0\t" ; $thism ++ ; } } $head .= "\n" ; print $head ; # print STDERR $head ; # finish lists for ( $n = 1 ; $n <= $N ; $n ++ ) { $thisn = $numnlist[$n] ; if ( $thisn ) { $nlist[$n] =~ s/\t$/\n/ ; print $nlist[$n] ; } } for ( $m = 1 ; $m <= $M ; $m ++ ) { $mlist[$m] =~ s/\t$/\n/ ; print $mlist[$m] ; } } sub mnadd { local($m,$n)=@_; if ($m>0) { # # put m and n on each others lists $nlist[$n] .= $m."\t" ; $mlist[$m] .= $n."\t" ; $numnlist[$n] ++ ; $nummlist[$m] ++ ; } }