Processing a Matrix
Posted: Fri Jan 23, 2004 7:41 pm
Looking to optimize a function, or see if anyone has an alternate approach to the core problem. Read the comments to see the
specifics.
peace
specifics.
Code: Select all
// Given a square (#rows = #cols) matrix
$sample_matrix = array(0 => ( 0, 3, 1),
1 => ( 0, 0, 2),
2 => ( 4, 2, 0));
// Call a function that removes both a row and column.
// For example, specifying an index of 1 would remove
// both the index 1 row, but also all index 1 columns
// from every other row as well.
// The matrix needs to also have the rows re-numbered
// so that there are no gaps. ie., 0,1,... not 0,2,....
// Finally the columns and rows need an ascending sort
// by index when finished.
$result = removeMatrixElement($sample_matrix, 1);
// $result matrix must be:
// array(0 => ( 0, 1),
// 1 => ( 4, 0));
// My current function... Looking for input on optimization
// and or alternate methodologies for accomplishing the
// task set forth above.
function removeMatrixElement($matrix, $index = NULL)
{
if ($index === NULL) {
// Default action is to pop the last element from $matrix.
for ($i = 0; $i < count($matrix); $i++) {
array_pop($matrixї$i]);
}
array_pop($matrix);
} else {
// Remove $index column from all rows.
for ($i = 0; $i < count($matrix); $i++) {
unset($matrixї$i]ї$index]);
// Renumber column keys to reflect deletion.
for ($j = $index + 1; $j < count($matrix); $j++) {
$matrixї$i]ї$j - 1] = $matrixї$i]ї$j];
}
ksort($matrixї$i]);
array_pop($matrixї$i]);
}
// Remove $index row.
unset($matrixї$index]);
// Renumber row keys to reflect deletion.
for ($i = $index + 1; $i < count($matrix); $i++) {
$matrixї$i - 1] = $matrixї$i];
}
ksort($matrix);
array_pop($matrix);
}
return $matrix;
}