PHP使用数组实现矩阵数学运算的方法示例


Posted in PHP onMay 29, 2017

本文实例讲述了PHP使用数组实现矩阵数学运算的方法。分享给大家供大家参考,具体如下:

矩阵运算就是对两个数据表进行某种数学运算,并得到另一个数据表.
下面的例子中我们创建了一个基本完整的矩阵运算函数库,以便用于矩阵操作的程序中.

来自 PHP5 in Practice  (U.S.)Elliott III & Jonathan D.Eisenhamer

<?php
// A Library of Matrix Math functions.
// All assume a Matrix defined by a 2 dimensional array, where the first
// index (array[x]) are the rows and the second index (array[x][y])
// are the columns
// First create a few helper functions
// A function to determine if a matrix is well formed. That is to say that
// it is perfectly rectangular with no missing values:
function _matrix_well_formed($matrix) {
  // If this is not an array, it is badly formed, return false.
  if (!(is_array($matrix))) {
    return false;
  } else {
    // Count the number of rows.
    $rows = count($matrix);
    // Now loop through each row:
    for ($r = 0; $r < $rows; $r++) {
      // Make sure that this row is set, and an array. Checking to
      // see if it is set is ensuring that this is a 0 based
      // numerically indexed array.
      if (!(isset($matrix[$r]) && is_array($matrix[$r]))) {
        return false;
      } else {
        // If this is row 0, calculate the columns in it:
        if ($r == 0) {
          $cols = count($matrix[$r]);
        // Ensure that the number of columns is identical else exit
        } elseif (count($matrix[$r]) != $cols) {
          return false;
        }
        // Now, loop through all the columns for this row
        for ($c = 0; $c < $cols; $c++) {
          // Ensure this entry is set, and a number
          if (!(isset($matrix[$r][$c]) &&
              is_numeric($matrix[$r][$c]))) {
            return false;
          }
        }
      }
    }
  }
  // Ok, if we actually made it this far, then we have not found
  // anything wrong with the matrix.
  return true;
}
// A function to return the rows in a matrix -
//  Does not check for validity, it assumes the matrix is well formed.
function _matrix_rows($matrix) {
  return count($matrix);
}
// A function to return the columns in a matrix -
//  Does not check for validity, it assumes the matrix is well formed.
function _matrix_columns($matrix) {
  return count($matrix[0]);
}
// This function performs operations on matrix elements, such as addition
// or subtraction. To use it, pass it 2 matrices, and the operation you
// wish to perform, as a string: '+', '-'
function matrix_element_operation($a, $b, $operation) {
  // Verify both matrices are well formed
  $valid = false;
  if (_matrix_well_formed($a) && _matrix_well_formed($b)) {
    // Make sure they have the same number of columns & rows
    $rows = _matrix_rows($a);
    $columns = _matrix_columns($a);
    if (($rows == _matrix_rows($b)) &&
        ($columns == _matrix_columns($b))) {
      // We have a valid setup for continuing with element math
      $valid = true;
    }
  }
  // If invalid, return false
  if (!($valid)) { return false; }
  // For each element in the matrices perform the operatoin on the
  // corresponding element in the other array to it:
  for ($r = 0; $r < $rows; $r++) {
    for ($c = 0; $c < $columns; $c++) {
      eval('$a[$r][$c] '.$operation.'= $b[$r][$c];');
    }
  }
  // Return the finished matrix:
  return $a;
}
// This function performs full matrix operations, such as matrix addition
// or matrix multiplication. As above, pass it to matrices and the
// operation: '*', '-', '+'
function matrix_operation($a, $b, $operation) {
  // Verify both matrices are well formed
  $valid = false;
  if (_matrix_well_formed($a) && _matrix_well_formed($b)) {
    // Make sure they have complementary numbers of rows and columns.
    // The number of rows in A should be the number of columns in B
    $rows = _matrix_rows($a);
    $columns = _matrix_columns($a);
    if (($columns == _matrix_rows($b)) &&
        ($rows == _matrix_columns($b))) {
      // We have a valid setup for continuing
      $valid = true;
    }
  }
  // If invalid, return false
  if (!($valid)) { return false; }
  // Create a blank matrix the appropriate size, initialized to 0
  $new = array_fill(0, $rows, array_fill(0, $rows, 0));
  // For each row in a ...
  for ($r = 0; $r < $rows; $r++) {
    // For each column in b ...
    for ($c = 0; $c < $rows; $c++) {
      // Take each member of column b, with each member of row a
      // and add the results, storing this in the new table:
      // Loop over each column in A ...
      for ($ac = 0; $ac < $columns; $ac++) {
        // Evaluate the operation
        eval('$new[$r][$c] += $a[$r][$ac] '.
          $operation.' $b[$ac][$c];');
      }
    }
  }
  // Return the finished matrix:
  return $new;
}
// A function to perform scalar operations. This means that you take the scalar value,
// and the operation provided, and apply it to every element.
function matrix_scalar_operation($matrix, $scalar, $operation) {
  // Verify it is well formed
  if (_matrix_well_formed($matrix)) {
    $rows = _matrix_rows($matrix);
    $columns = _matrix_columns($matrix);
    // For each element in the matrix, multiply by the scalar
    for ($r = 0; $r < $rows; $r++) {
      for ($c = 0; $c < $columns; $c++) {
        eval('$matrix[$r][$c] '.$operation.'= $scalar;');
      }
    }
    // Return the finished matrix:
    return $matrix;
  } else {
    // It wasn't well formed:
    return false;
  }
}
// A handy function for printing matrices (As an HTML table)
function matrix_print($matrix) {
  // Verify it is well formed
  if (_matrix_well_formed($matrix)) {
    $rows = _matrix_rows($matrix);
    $columns = _matrix_columns($matrix);
    // Start the table
    echo '<table>';
    // For each row in the matrix:
    for ($r = 0; $r < $rows; $r++) {
      // Begin the row:
      echo '<tr>';
      // For each column in this row
      for ($c = 0; $c < $columns; $c++) {
        // Echo the element:
        echo "<td>{$matrix[$r][$c]}</td>";
      }
      // End the row.
      echo '</tr>';
    }
    // End the table.
    echo "</table>/n";
  } else {
    // It wasn't well formed:
    return false;
  }
}
// Let's do some testing. First prepare some formatting:
echo "<mce:style><!--
table { border: 1px solid black; margin: 20px; }
td { text-align: center; }
--></mce:style><style mce_bogus="1">table { border: 1px solid black; margin: 20px; }
td { text-align: center; }</style>/n";
// Now let's test element operations. We need identical sized matrices:
$m1 = array(
  array(5, 3, 2),
  array(3, 0, 4),
  array(1, 5, 2),
  );
$m2 = array(
  array(4, 9, 5),
  array(7, 5, 0),
  array(2, 2, 8),
  );
// Element addition should give us: 9  12   7
//                 10   5   4
//                  3   7  10
matrix_print(matrix_element_operation($m1, $m2, '+'));
// Element subtraction should give us:   1  -6  -3
//                    -4  -5   4
//                    -1   3  -6
matrix_print(matrix_element_operation($m1, $m2, '-'));
// Do a scalar multiplication on the 2nd matrix:  8 18 10
//                        14 10  0
//                         4  4 16
matrix_print(matrix_scalar_operation($m2, 2, '*'));
// Define some matrices for full matrix operations.
// Need to be complements of each other:
$m3 = array(
  array(1, 3, 5),
  array(-2, 5, 1),
  );
$m4 = array(
  array(1, 2),
  array(-2, 8),
  array(1, 1),
  );
// Matrix multiplication gives: 0  31
//                -11  37
matrix_print(matrix_operation($m3, $m4, '*'));
// Matrix addition gives:   9 20
//              4 15
matrix_print(matrix_operation($m3, $m4, '+'));
?>
PHP 相关文章推荐
模仿OSO的论坛(三)
Oct 09 PHP
一个基于PDO的数据库操作类(新) 一个PDO事务实例
Jul 03 PHP
Php中用PDO查询Mysql来避免SQL注入风险的方法
Apr 25 PHP
discuz加密解密函数使用方法和中文注释
Jan 21 PHP
xss防御之php利用httponly防xss攻击
Mar 21 PHP
PHP防止表单重复提交的几种常用方法汇总
Aug 19 PHP
浅谈php正则表达式中的非贪婪模式匹配的使用
Nov 25 PHP
php metaphone()函数的定义和用法
May 15 PHP
深入理解PHP中的count函数
May 31 PHP
实例讲解YII2中多表关联的使用方法
Jul 21 PHP
PHP对称加密算法(DES/AES)类的实现代码
Nov 14 PHP
Apache+PHP+MySQL搭建PHP开发环境图文教程
Aug 06 PHP
PHP实现蛇形矩阵,回环矩阵及数字螺旋矩阵的方法分析
May 29 #PHP
PHP实现的简单AES加密解密算法实例
May 29 #PHP
PHP编程求最大公约数与最小公倍数的方法示例
May 29 #PHP
使用一个for循环将N*N的二维数组的所有值置1实现方法
May 29 #PHP
PHP 网站修改默认访问文件的nginx配置
May 27 #PHP
yii插入数据库防并发的简单代码
May 27 #PHP
[原创]php正则删除img标签的方法示例
May 27 #PHP
You might like
《星际争霸重制版》兵种对比图鉴
2020/03/02 星际争霸
针对多用户实现头像上传功能PHP代码 适用于登陆页面制作
2016/08/17 PHP
关于恒等于(===)和非恒等于(!==)
2007/08/20 Javascript
javascript innerText和innerHtml应用
2010/01/28 Javascript
js获取浏览器的可视区域尺寸的实现代码
2011/11/30 Javascript
JS定时器实例
2013/04/17 Javascript
js操作label给label赋值及取label的值示例
2013/11/07 Javascript
jQuery Ajax 异步加载显示等待效果代码分享
2016/08/01 Javascript
webpack入门+react环境配置
2017/02/08 Javascript
VUE 更好的 ajax 上传处理 axios.js实现代码
2017/05/10 Javascript
利用vscode编写vue的简单配置详解
2017/06/17 Javascript
vue 计时器组件的实现代码
2017/09/14 Javascript
JS实现的文字间歇循环滚动效果完整示例
2018/02/13 Javascript
vue项目base64字符串转图片的实现代码
2018/07/13 Javascript
JavaScript显式数据类型转换详解
2019/03/18 Javascript
关于layui时间回显问题的解决方法
2019/09/24 Javascript
vue点击标签切换选中及互相排斥操作
2020/07/17 Javascript
五句话帮你轻松搞定js原型链
2020/12/09 Javascript
[03:53]2016国际邀请赛中国区预选赛第三日TOP10精彩集锦
2016/06/29 DOTA
python中的多线程实例教程
2014/08/27 Python
Python编程之属性和方法实例详解
2015/05/19 Python
Python制作钉钉加密/解密工具
2016/12/07 Python
利用python微信库itchat实现微信自动回复功能
2017/05/18 Python
python中将一个全部为int的list 转化为str的list方法
2018/04/09 Python
python 实现将字典dict、列表list中的中文正常显示方法
2018/07/06 Python
python关于调用函数外的变量实例
2019/12/26 Python
Python Socketserver实现FTP文件上传下载代码实例
2020/03/27 Python
python 制作本地应用搜索工具
2021/02/27 Python
SQL Server提供的3种恢复模型都是什么? 有什么区别?
2012/05/13 面试题
公司出纳岗位职责
2013/12/07 职场文书
超市促销活动总结
2014/07/01 职场文书
商铺消防安全责任书
2014/07/29 职场文书
诉讼代理人授权委托书
2014/10/11 职场文书
倡议书作文
2015/01/19 职场文书
幼儿园个人师德总结
2015/02/06 职场文书
使用python如何删除同一文件夹下相似的图片
2021/05/07 Python