my @sparse = () ; while (...whatever...) { my $value = ... ; # next value my $col = ... ; # in this column my $row = ... ; # and this row if ($value) { # keep only the non-zeros push @sparse, [$col, $row, $value] ; } ; } ; @sparse = sort { ($$a[0] <=> $$b[0]) || ($$a[1] <=> $$b[1]) || die } @sparse ; #### use strict ; use warnings ; my @sparse = () ; my $col = 0 ; # emerges from loop set to # of columns my $row = 0 ; # emerges from loop set to # of rows while () { s/\s+/ /g ; s/^ // ; s/ $// ; $col = 0 ; foreach my $val (split / /) { if ($val) { push @sparse, [$col, $row, $val] ; } ; ++$col ; } ; ++$row ; } ; @sparse = sort { ($$a[0] <=> $$b[0]) || ($$a[1] <=> $$b[1]) || die } @sparse ; my $Ap = 0 ; print "Ap = $Ap" ; my $c = 0 ; foreach my $a (@sparse) { while ($c < $$a[0]) { print " $Ap" ; ++$c ; } ; ++$Ap ; } ; while ($c++ < $col) { print " $Ap" ; } ; print "\n" ; print "Ai =" ; foreach my $a (@sparse) { print " $$a[1]" ; } ; print "\n" ; print "Ax =" ; foreach my $a (@sparse) { print " $$a[2]" ; } ; print "\n" ; __DATA__ 2 3 0 0 0 3 0 4 0 6 0 -1 -3 2 0 0 0 1 0 0 0 4 2 0 1