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使用者状态管理功能的应用
Oct 09 PHP
php引用地址改变变量值的问题
Mar 23 PHP
PHP最常用的2种设计模式工厂模式和单例模式介绍
Aug 14 PHP
file_get_contents获取不到网页内容的解决方法
Mar 07 PHP
php实现单链表的实例代码
Mar 22 PHP
php中的filesystem文件系统函数介绍及使用示例
Feb 13 PHP
PHP数组函数array_multisort()用法实例分析
Apr 02 PHP
php实现将base64格式图片保存在指定目录的方法
Oct 13 PHP
PHP中非常有用却鲜有人知的函数集锦
Aug 17 PHP
laravel框架实现去掉URL中index.php的方法
Oct 12 PHP
phpQuery采集网页实现代码实例
Apr 02 PHP
PHP7 windows支持
Mar 09 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
PHP6 先修班 JSON实例代码
2008/08/23 PHP
支持中文和其他编码的php截取字符串函数分享(截取中文字符串)
2014/03/13 PHP
PHP实现搜索地理位置及计算两点地理位置间距离的实例
2016/01/08 PHP
PHP树形结构tree类用法示例
2019/02/01 PHP
Laravel框架实现的上传图片到七牛功能详解
2019/09/06 PHP
JS 参数传递的实际应用代码分析
2009/09/13 Javascript
使用iframe window的scroll方法控制iframe页面滚动
2014/03/05 Javascript
js动态修改整个页面样式达到换肤效果
2014/05/23 Javascript
再谈javascript原型继承
2014/11/10 Javascript
js省市县三级联动效果实例
2020/04/15 Javascript
jQuery实现的网页换肤效果示例
2016/09/20 Javascript
微信公众号-获取用户信息(网页授权获取)实现步骤
2016/10/21 Javascript
详解vue之页面缓存问题(基于2.0)
2017/01/10 Javascript
解决vue.js在编写过程中出现空格不规范报错的问题
2017/09/20 Javascript
js 开发之autocomplete=&quot;off&quot;在chrom中失效的解决办法
2017/09/28 Javascript
React Native基础入门之初步使用Flexbox布局
2018/07/02 Javascript
Vue.js实现双向数据绑定方法(表单自动赋值、表单自动取值)
2018/08/27 Javascript
Vue.js@2.6.10更新内置错误处机制Fundebug同步支持相应错误监控
2019/05/13 Javascript
jQuery创建折叠式菜单
2019/06/15 jQuery
python Spyder界面无法打开的解决方法
2018/04/27 Python
python实现贪吃蛇游戏
2020/03/21 Python
详解python爬虫系列之初识爬虫
2019/04/06 Python
浅谈Django QuerySet对象(模型.objects)的常用方法
2020/03/28 Python
python装饰器实现对异常代码出现进行自动监控的实现方法
2020/09/15 Python
Python爬虫回测股票的实例讲解
2021/01/22 Python
曼联官方网上商店:Manchester United Direct
2017/07/28 全球购物
任意存:BOXFUL
2018/05/21 全球购物
ONLY瑞典官网:世界知名服装品牌
2018/06/19 全球购物
优秀共产党员先进事迹
2014/01/27 职场文书
爱护环境卫生倡议书
2015/04/29 职场文书
实习介绍信范文
2015/05/05 职场文书
董事长助理工作总结2015
2015/07/23 职场文书
2019学校请假条格式及范文
2019/06/25 职场文书
Vue3中的Refs和Ref详情
2021/11/11 Vue.js
Python 数据可视化工具 Pyecharts 安装及应用
2022/04/20 Python
Python软件包安装的三种常见方法
2022/07/07 Python