PHP中的矩阵乘法 [英] Matrix multiplication in php

查看:108
本文介绍了PHP中的矩阵乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管矩阵的顺序应该很好,但是以下代码会抛出异常.这可能是我无法注意到的小事,但无法弄清.

Although the order of matrices should be fine, the following code throws back the exception. It might be a tiny thing I'm not being able to notice, but can't figure it out.

<?php
  $mat1 = array(5,1);
  $mat2 = array(1,5);
  function matrixmult($m1,$m2){
    $r=count($m1);
    $c=count($m2[0]);
    $p=count($m2);
    if(count($m1[0])!=$p){throw new Exception('Incompatible matrixes');}
      $m3=array();
      for ($i=0;$i< $r;$i++){
        for($j=0;$j<$c;$j++){
          $m3[$i][$j]=0;
          for($k=0;$k<$p;$k++){
            $m3[$i][$j]+=$m1[$i][$k]*$m2[$k][$j];
          }
        }
      }
    }
    return($m3);
  }
  matrixmult($mat1,$mat2);
?>

推荐答案

您通过两种方式指定了错误的测试矩阵:

You're specifying your test matrices wrong, in two ways:

  1. 数组不是二维的(即数字数组).
  2. 即使将另一个array( )包裹在它们周围,第一个矩阵的宽度等于第二个矩阵的高度的条件对于[5 1]和[1 5]也不成立. 2宽1高.
  1. The arrays aren't two-dimensional (that is, arrays of arrays of numbers).
  2. Even if you wrapped another array( ) around them, the condition that the width of the first matrix be equal to the height of the second matrix doesn't hold with [5 1] and [1 5], which are both 2 wide and 1 high.

您需要的是类似的东西

$mat1 = array(array(5,1));
$mat2 = array(array(1),array(5));

这篇关于PHP中的矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆