Skip to content

Commit 1e8a82e

Browse files
Merge pull request #347 from SHQHDMR/master
php实现矩阵乘法
2 parents d89ba1f + 261bcb9 commit 1e8a82e

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<?php
2+
3+
function popRow(&$matrix)
4+
{
5+
return empty($matrix) ? [] : [array_shift($matrix)];
6+
}
7+
8+
function popColumn(&$matrix)
9+
{
10+
$column = [];
11+
12+
foreach ($matrix as $key => &$row) {
13+
$data = array_shift($row);
14+
if (empty($data) || empty($row)) {
15+
unset($matrix[$key]);
16+
}
17+
$column[] = [$data];
18+
}
19+
return $column;
20+
}
21+
22+
function countProduction($row, $column)
23+
{
24+
for ($i = 0, $sum = 0; $i < count($row[0]); $i++) {
25+
$sum += $row[0][$i] * $column[$i][0];
26+
}
27+
return $sum;
28+
}
29+
30+
function merger($value1, $value2, $value3, $value4)
31+
{
32+
if (empty($value2) && empty($value3)) {
33+
return $value1;
34+
} else {
35+
$array12 = array_merge([$value1], !is_array($value2) ? [$value2] : $value2);
36+
if (!is_array($value3)) {
37+
$array34 = array_merge([$value3], !is_array($value4) ? [$value4] : $value4);
38+
return [$array12, $array34];
39+
} else {
40+
for ($i = 0, $array34 = []; $i < count($value3); $i++) {
41+
$array34[] = array_merge($value3[$i], $value4[$i]);
42+
}
43+
return array_merge([$array12], $array34);
44+
}
45+
}
46+
}
47+
48+
function matrixProduction($matrix1, $matrix2)
49+
{
50+
$row = popRow($matrix1);
51+
$column = popColumn($matrix2);
52+
53+
if (empty($row) || empty($column)) {
54+
return [];
55+
}
56+
57+
$value1 = countProduction($row, $column);
58+
$value2 = matrixProduction($row, $matrix2);
59+
$value3 = matrixProduction($matrix1, $column);
60+
$value4 = matrixProduction($matrix1, $matrix2);
61+
62+
return merger($value1, $value2, $value3, $value4);
63+
}
64+
65+
$matrix1 = [
66+
[1, 2, 3],
67+
[4, 5, 6],
68+
[7, 8, 9],
69+
];
70+
71+
$matrix2 = [
72+
[1, 2, 3],
73+
[4, 5, 6],
74+
[7, 8, 9],
75+
];
76+
77+
var_dump(matrixProduction($matrix1, $matrix2));

0 commit comments

Comments
 (0)