降低PHP中矩阵序的有效方法

时间:2019-03-31 05:11:35

标签: php performance matrix determinants

我正在用PHP开发行列式计算器

在Matrix类中,我创建了一些函数,其中包括calc(顺序,矩阵)函数。 此函数调用另一个函数以将数组的阶降低到$ order = 3,然后执行sarrus($ matriz)函数。

  

注意:该矩阵变量将在每次降低订单时更改,即原始矩阵将保存在另一个变量中!

好吧,我想知道将数组顺序降低到3的最佳方法,如果可能的话,我尝试使用laplace,但是在循环中我感到很困惑,我决定放弃一会儿。 / p>

public function calc ($order, $matriz)
{
    // If the order equals 1: the element is the determinant
    if ($order == 1) {
        $ this->det = $matriz[0][0];
    }
    // If the order equals 2: call the @segOrder function
    else if ($order == 2) {
        segOrder($matriz);
    }
    // If the order is 3: call the function @sarrus
    else if ($order == 3) {
        sarrus($matriz);
    }
    // If the order is greater than 3: call the function @leaveOrder to lower the array order to 3 and then use @sarrus to have the determinant
    else if ($order > 3) {
        $matriz = lowerOrder($matriz, $order);
        sarrus($matriz);
    }
    return $this->det;
}

阵列布局:

$matriz = array (
            array (1,2,3),
            array (4,5,6),
            array (7,8,9)
          );

1 个答案:

答案 0 :(得分:0)

我认为您要的是这样的东西...

/**
 * Truncates rows and columns from an array of arrays (ignoring rows/columns beyond a certain index).
 *
 * The returned value will have numeric indexes regardless of what you pass in.
 *
 * @param array $matrix
 * @param int $row_cap
 * @param int $col_cap
 * @return array
 */
function matrix_slice( array $matrix, $row_cap = 3, $col_cap = 3 ) {
    return array_map( function( $vector ) use( $col_cap ){
        return array_slice( array_values( $vector ), 0, $col_cap );
    }, array_slice( array_values( $matrix ), 0, $row_cap ) );
}