矩阵乘法递归求解
Posted shqhdmr
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了矩阵乘法递归求解相关的知识,希望对你有一定的参考价值。
给定两个N×N的矩阵,求乘积
如下图所示,乘法执行过程如下:
1.矩阵1先拿出一行,矩阵2先拿出一列
2.行与列相乘得到value1
3.行与剩下矩阵2相乘得到value2(递归过程)
4.剩下矩阵1与列相乘得到value3(递归过程)
5.剩下矩阵1与剩下矩阵2相乘得到value4(递归过程)
6.将value1~value4合并成结果数组
写代码时注意约定,value1一定是数值,value2、value3、value4是数值、空数组或者非空的二维数组
由php实现,大体思路不难,但是要非常注意合并结果的细节:
1 <?php 2 3 class MatrixProduct 4 5 protected $matrix1, $matrix2; 6 protected $result; 7 8 public function __construct($matrix1, $matrix2) 9 10 $this->matrix1 = $matrix1; 11 $this->matrix2 = $matrix2; 12 $this->result = $this->matrixProduction($this->matrix1, $this->matrix2); 13 14 15 public function show() 16 17 foreach ($this->result as $row) 18 foreach ($row as $data) 19 printf(‘%5d‘, $data); 20 21 echo PHP_EOL; 22 23 24 25 protected function popRow(&$matrix) 26 27 return empty($matrix) ? [] : [array_shift($matrix)]; 28 29 30 protected function popColumn(&$matrix) 31 32 $column = []; 33 foreach ($matrix as $key => &$row) 34 $data = array_shift($row); 35 if (empty($data) || empty($row)) 36 unset($matrix[$key]); 37 38 $column[] = [$data]; 39 40 return $column; 41 42 43 protected function countProduction($row, $column) 44 45 for ($i = 0, $sum = 0; $i < count($row[0]); $i++) 46 $sum += $row[0][$i] * $column[$i][0]; 47 48 return $sum; 49 50 51 protected function merger($value1, $value2, $value3, $value4) 52 53 if (empty($value2) && empty($value3)) 54 return $value1; 55 else 56 $array12 = array_merge([$value1], !is_array($value2) ? [$value2] : $value2[0] ?? []); 57 if (!is_array($value3)) 58 $array34 = array_merge([$value3], !is_array($value4) ? [$value4] : $value4[0] ?? []); 59 return [$array12, $array34]; 60 else 61 for ($i = 0, $array34 = []; $i < count($value3); $i++) 62 $array34[] = array_merge($value3[$i], $value4[$i] ?? []); 63 64 return array_merge([$array12], $array34); 65 66 67 68 69 protected function matrixProduction($matrix1, $matrix2) 70 71 $row = $this->popRow($matrix1); 72 $column = $this->popColumn($matrix2); 73 if (empty($row) || empty($column)) 74 return []; 75 76 77 $value1 = $this->countProduction($row, $column); 78 $value2 = $this->matrixProduction($row, $matrix2); 79 $value3 = $this->matrixProduction($matrix1, $column); 80 $value4 = $this->matrixProduction($matrix1, $matrix2); 81 82 return $this->merger($value1, $value2, $value3, $value4); 83 84 85 86 $matrix1 = [ 87 [1, 2, 3, 4], 88 [1, 2, 3, 4], 89 [1, 2, 3, 4], 90 [1, 2, 3, 4], 91 ]; 92 93 $matrix2 = [ 94 [1, 2, 3, 4], 95 [5, 6, 7, 8], 96 [9, 10, 11, 12], 97 [13, 14, 15, 16] 98 ]; 99 100 $production = new MatrixProduct($matrix1, $matrix2); 101 $production->show();
以上是关于矩阵乘法递归求解的主要内容,如果未能解决你的问题,请参考以下文章