【问题标题】:Multidimensional array multiplication多维数组乘法
【发布时间】:2013-06-05 13:22:11
【问题描述】:

假设我想要一个复制矩阵乘法的 PHP 代码,我的矩阵如下所示:

$matrix_1 = array(array(1,2), array(3,4))

子数组的个数(2)相当于矩阵的列数,而每个子数组的元素个数(2)代表矩阵的个数矩阵中的行。

代码需要:

  • 考虑不同维度的矩阵。
  • 识别两个矩阵何时不能相乘(矩阵 A 中的列数与矩阵 B 中的行数不同)。
  • 可能是标量乘法,其中矩阵的每个元素都乘以一个常数。

我附上了幻灯片here,解释了代码应该实现的目标(带有两个示例)。

【问题讨论】:

  • 这是你的作业吗?
  • 这可能是也可能不是我的作业!我试过谷歌搜索,但大多数解决方案有点乱?假设我应该自己尝试一下!
  • 到目前为止你做了什么?
  • 到目前为止非常不雅的东西 - 只是拼接数组并从中形成新数组。此外,我还没有针对所有矩阵维度的通用解决方案 - 目前主要使用方阵。
  • @user2468585,使用上面的链接

标签: php arrays matrix multidimensional-array multiplication


【解决方案1】:

这是我的(冗长的)解决方案。我将尝试看看是否可以在某些地方简化它。请注意:

  • 此解决方案不考虑标量乘法,但如果您想包含它,这相对容易合并。假设一个标量是一个单元素数组——在这种情况下,在else 命令中只需包含一个count() 命令来识别一个(或多个)数组是否是一个标量并相应地使用array_map 应用一个乘法函数.
  • 我假设数组遵循矩阵形式 - 例如一栏 不能有比另一个更多的元素。你可以解释这个 正式地通过确保每个子数组具有相同数量的 元素。

代码:

<?php

// FUNCTIONS

function mul($x, $y){
    return ($x * $y);
}

// Example Arrays

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

// Check for row/column equivalence

$array_1_cols = count($array_1);
$array_1_rows = count($array_1[0]);
$array_2_cols = count($array_2);
$array_2_rows = count($array_2[0]);

// Check to see if matrix multiplication is possible

if($array_1_cols == $array_2_rows) {

$m_cols = $array_2_cols;
$m_rows = $array_1_rows;

$array_3 = array();
$col_index = 1;

// Start loop for each column of the new matrix

while($col_index <= $m_cols) {
$m_col_index = $col_index - 1;
$sub_array[$col_index] = array();

// Start loop for each row of the new matrix

$row_index = 1;
while($row_index <= $m_rows) {
$m_row_index = $row_index - 1;

// Auxiliary array for each row of A
$a_row[$row_index] = array();

$a_index = 1;
while($a_index <= $array_1_cols) {
$start_p = $a_index - 1;
$el_part_[$a_index] = $array_1[$start_p];
$el_part_[$a_index] = $el_part_[$a_index][$m_row_index];
array_push($a_row[$row_index], $el_part_[$a_index]);
++$a_index;
}

// Array for columns of B

$b_col[$col_index] = $array_2[$m_col_index];

// Build matrix C - defined over the rows of A and the columns of B

$c_part[$row_index][$col_index] = array_map('mul', $a_row[$row_index], $b_col[$col_index]);

$c_el[$row_index][$col_index] = array_sum($c_part[$row_index][$col_index]);

array_push($sub_array[$col_index], $c_el[$row_index][$col_index]);

// End row loop

++$row_index;
}

array_push($array_3,$sub_array[$col_index]);

++$col_index;
}

print_r($array_3);

} else {

echo "This is not possible!";

}


?>

【讨论】:

    猜你喜欢
    • 2013-09-23
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多