Skip to content

matrix::colAsVector function incorrectly using $this->row as multiplier #4

@sneakyimp

Description

@sneakyimp

The colAsVector method clearly has a problem. Some simple code to illustrate:

require __DIR__ . '/vendor/autoload.php';
use Np\matrix;
$v = matrix::ar([
	[1,2,3,4,5,6],
	[7,8,9,10,11,12]
]);
echo $v, "\n";
$shape = $v->getShape();
for($i=0; $i<$shape->n; $i++) {
	$vect = $v->colAsVector($i);
	echo $vect, "\n";
}

The output is clearly wrong, and shows the second item in each column drifting off from the correct value.

Np\matrix
1.000000  2.000000  3.000000  4.000000  5.000000  6.000000  
7.000000  8.000000  9.000000  10.000000  11.000000  12.000000  

Np\vector
1.000000  3.000000  

Np\vector
2.000000  4.000000  

Np\vector
3.000000  5.000000  

Np\vector
4.000000  6.000000  

Np\vector
5.000000  7.000000  

Np\vector
6.000000  8.000000  

I believe this modified version of the function may remedy the problem:

    /**
     * Return a col as vector from the matrix.
     * @param int $index
     * @return \Np\vector
     */
    public function colAsVector(int $index): vector {
        $vr = vector::factory($this->row);
        for ($i = 0; $i < $this->row; $i++) {
            $vr->data[$i] = $this->data[($i *  $this->col) + $index];
        }
        return $vr;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions