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 相关文章推荐
怎样在UNIX系统下安装MySQL
Oct 09 PHP
php中将图片gif,jpg或mysql longblob或blob字段值转换成16进制字符串
Aug 23 PHP
phpmailer发送邮件之后,返回收件人是否阅读了邮件的方法
Jul 19 PHP
用php来限制每个ip每天浏览页面数量的实现思路
Feb 24 PHP
php上传文件并存储到mysql数据库的方法
Mar 16 PHP
浅析PHP关键词替换的类(避免重复替换,保留与还原原始链接)
Sep 22 PHP
PHP使用socket发送HTTP请求的方法
Feb 14 PHP
php实现无限级分类查询(递归、非递归)
Mar 10 PHP
PHP实现求连续子数组最大和问题2种解决方法
Dec 26 PHP
PHP命名空间与自动加载机制的基础介绍
Aug 25 PHP
yii 框架实现按天,月,年,自定义时间段统计数据的方法分析
Apr 04 PHP
用php如何解决大文件分片上传问题
Jul 07 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
php获取网页内容方法总结
2008/12/04 PHP
php+xml编程之xpath的应用实例
2015/01/24 PHP
Zend Framework入门应用实例详解
2016/12/11 PHP
PHP 数组操作详解【遍历、指针、函数等】
2020/05/13 PHP
发现的以前不知道的函数
2006/09/19 Javascript
JavaScript实现页面5秒后自动跳转的方法
2015/04/16 Javascript
jQuery实现表格展开与折叠的方法
2015/05/04 Javascript
angularjs创建弹出框实现拖动效果
2020/08/25 Javascript
js日期插件dateHelp获取本月、三个月、今年的日期
2016/03/07 Javascript
jQuery代码实现表格中点击相应行变色功能
2016/05/09 Javascript
jQuery实现的可编辑表格完整实例
2016/06/20 Javascript
基于vue实现swipe轮播组件实例代码
2017/05/24 Javascript
详解微信第三方小程序代开发
2017/06/23 Javascript
深入浅析Node.js 事件循环、定时器和process.nextTick()
2018/10/22 Javascript
深入了解JavaScript 私有化
2019/05/30 Javascript
微信小程序如何使用canvas二维码保存至手机相册
2019/07/15 Javascript
js实现简单的无缝轮播效果
2020/09/05 Javascript
vue 动态创建组件的两种方法
2020/12/31 Vue.js
[02:37]2015国际邀请赛选手档案—LGD.Xiao8
2015/07/28 DOTA
python检测是文件还是目录的方法
2015/07/03 Python
Python连接MySQL并使用fetchall()方法过滤特殊字符
2016/03/13 Python
Python基于scapy实现修改IP发送请求的方法示例
2017/07/08 Python
python密码错误三次锁定(实例讲解)
2017/11/14 Python
Python ini文件常用操作方法解析
2020/04/26 Python
基于pandas向csv添加新的行和列
2020/05/25 Python
Roxy荷兰官方网站:冲浪、滑雪板、服装和配件
2019/10/22 全球购物
房屋买卖协议书范本
2014/04/10 职场文书
国旗下演讲稿
2014/05/08 职场文书
幼儿园标语大全
2014/06/19 职场文书
上课迟到检讨书300字
2014/10/15 职场文书
入党函调证明材料
2014/12/24 职场文书
餐饮服务食品安全承诺书
2015/04/29 职场文书
幼儿园圣诞节活动总结
2015/05/06 职场文书
2019行政前台转正申请书范文3篇
2019/08/15 职场文书
Django利用AJAX技术实现博文实时搜索
2021/05/06 Python
pytorch中的 .view()函数的用法介绍
2022/03/17 Python