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 相关文章推荐
php 正则表达式小结
Aug 31 PHP
全局记录程序片段的运行时间 正确找到程序逻辑耗时多的断点
Jan 06 PHP
PHP下打开phpMyAdmin出现403错误的问题解决方法
May 23 PHP
PHP中对缓冲区的控制实现代码
Sep 29 PHP
Thinkphp中的curd应用实用要点
Jan 04 PHP
基于php的微信公众平台开发入门实例
Apr 15 PHP
php生成过去100年下拉列表的方法
Jul 20 PHP
如何用PHP来实现一个动态Web服务器
Jul 29 PHP
利用PHP将部分内容用星号替换
Apr 21 PHP
php实现的农历算法实例
Aug 11 PHP
盘点PHP和ASP.NET的10大对比!
Dec 24 PHP
smarty自定义函数用法示例
May 20 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
laravel安装和配置教程
2014/10/29 PHP
搭建基于Docker的PHP开发环境的详细教程
2015/07/01 PHP
CI框架常用函数封装实例
2016/11/21 PHP
js编写trim()函数及正则表达式的运用
2013/10/24 Javascript
js和jquery如何获取图片真实的宽度和高度
2014/09/28 Javascript
JavaScript中Number.MAX_VALUE属性的使用方法
2015/06/04 Javascript
Jquery ajax加载等待执行结束再继续执行下面代码操作
2015/11/24 Javascript
js实现精确到秒的日期选择器完整实例
2016/04/30 Javascript
Node.js中防止错误导致的进程阻塞的方法
2016/08/11 Javascript
JQ图片文件上传之前预览功能的简单实例(分享)
2017/11/12 Javascript
关于jquery layui弹出层的使用方法
2018/04/21 jQuery
基于jquery实现左右上下移动效果
2018/05/02 jQuery
Vue中实现权限控制的方法示例
2019/06/07 Javascript
使用p5.js实现动态GIF图片临摹重现
2019/10/23 Javascript
JavaScript交换两个变量方法实例
2019/11/25 Javascript
python将字符串转换成数组的方法
2015/04/29 Python
python实现简单的socket server实例
2015/04/29 Python
浅析python中numpy包中的argsort函数的使用
2018/08/30 Python
python 高效去重复 支持GB级别大文件的示例代码
2018/11/08 Python
python实现批量视频分帧、保存视频帧
2019/05/31 Python
Python并发请求下限制QPS(每秒查询率)的实现代码
2020/06/05 Python
基于css3 animate制作绚丽的动画效果
2015/11/24 HTML / CSS
经典C++面试题一
2016/11/06 面试题
机械专业个人求职自荐信格式
2013/09/21 职场文书
数据员岗位职责
2013/11/19 职场文书
玲玲的画教学反思
2014/02/04 职场文书
生物科学专业职业规划书范文
2014/02/11 职场文书
税务干部鉴定材料
2014/02/11 职场文书
初三学习决心书
2014/03/11 职场文书
教师应聘自荐信范文
2014/03/14 职场文书
企业精细化管理实施方案
2014/03/23 职场文书
岗位廉政承诺书
2014/03/27 职场文书
机关会计岗位职责
2014/04/08 职场文书
女方家长婚礼答谢词
2015/09/29 职场文书
Python离线安装openpyxl模块的步骤
2021/03/30 Python
台式电脑蓝牙适配器怎么安装?台式电脑蓝牙适配器安装教程
2022/04/08 数码科技