Angharad has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks
I've already posted once on this topic today. I have gotten a little further but alas have got somewhat stuck. Basically, I have a dataset in the form of a matrix and I want to perform SVD on this dataset and then reconstruct the matrix with the most signficant data. I already have the code in the form of a Matlab M script so have been trying to convert it into perl using the PDL module. Here is the perl script so far (please bear in mind that I'm using a test dataset here, the real one will be much bigger).
#!/usr/bin/perl use PDL; my $a = pdl [ [ 0.6490, 0.0330, 0.1670, 0.3700], [ 0.1150, 0.0290, 0.0480, 0.0650], [ 0.0070, 0.3570, 0.3870, 0.2010], [ 0.0630, 0.0760, 0.0540, 0.0560], [ 0, 0.0400, 0.0160, 0.0160], [ 0.0120, 0.0620, 0.0430, 0.0380], [ 0.1530, 0.4020, 0.2850, 0.2550], ]; ($U, $S, $V) = svd($a); # create square matrix for 'S' @valuesS = list $S; $SqS = pdl [ [ $valuesS[0], 0, 0, 0], [ 0, $valuesS[1], 0, 0], [ 0, 0, $valuesS[2], 0], [ 0, 0, 0, $valuesS[3]], ]; # transpose V $Vt = $V->transpose(); $Us = $U->slice('0:1,0:6'); $Ss = $SqS->slice('0:1,0:1'); $Vs = $Vt->slice('0:3,0:1'); print "$Us\n"; print "$Ss\n"; print "$Vs\n"; $recA = $Us * $Ss * $Vs; print "$recA\n";
Most of this works just fine, but not this line
$recA = $Us * $Ss * $Vs;
Where I get the following error
PDL: PDL::Ops::mult(a,b,c): Parameter 'b' PDL barfed: Mismatched implicit thread dimension 1: should be 7, is 2
I *think* this is due to the fact that the three matrixes I am trying to multiply are of differeing dimensions. I am trying to emulate the following matlab command
recA = U(:,1:ns)*S(1:ns,1:ns)*Vt(1:ns,:)
Any suggestions as to a work around appreciated folks :)

Replies are listed 'Best First'.
Re: Arrgghh! Perl and Matlab (round 2)
by ambrus (Abbot) on Aug 12, 2005 at 16:36 UTC

    Try the x operator for matrix multiplication.

Re: Arrgghh! Perl and Matlab (round 2)
by tall_man (Parson) on Aug 12, 2005 at 23:00 UTC
    There's an easier way to create your $Sqs matrix. I tried this with your example and the suggestion by ambrus about matrix multiplication, and it worked.
    $Sqs = zeroes($V); $Sqs->diagonal(0,1) .= $S;

      There's an even easier way:

      $Sqs = stretcher($S);
      see PDL::MatrixOps.
Re: Arrgghh! Perl and Matlab (round 2)
by Angharad (Pilgrim) on Aug 15, 2005 at 09:51 UTC
    Thanks everyone for the advice :)