Page 1 of 1

Processing a Matrix

Posted: Fri Jan 23, 2004 7:41 pm
by ilovetoast
Looking to optimize a function, or see if anyone has an alternate approach to the core problem. Read the comments to see the
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++) &#123;
			array_pop($matrix&#1111;$i]);
		&#125;
		array_pop($matrix);
	&#125; else &#123;
		// Remove $index column from all rows.
		for ($i = 0; $i < count($matrix); $i++) &#123;
			unset($matrix&#1111;$i]&#1111;$index]);
			
			// Renumber column keys to reflect deletion.
			for ($j = $index + 1; $j < count($matrix); $j++) &#123;
				$matrix&#1111;$i]&#1111;$j - 1] = $matrix&#1111;$i]&#1111;$j];
			&#125;
			ksort($matrix&#1111;$i]);
			array_pop($matrix&#1111;$i]);
		&#125;
		
		// Remove $index row.
		unset($matrix&#1111;$index]);
		
		// Renumber row keys to reflect deletion.
		for ($i = $index + 1; $i < count($matrix); $i++) &#123;
			$matrix&#1111;$i - 1] = $matrix&#1111;$i];
		&#125;
		ksort($matrix);
		array_pop($matrix);
	&#125;
	
	return $matrix;
&#125;
peace