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应用程序来获取Web服务器的状态信息
Oct 09 PHP
推荐文章系统(一)
Oct 09 PHP
php简单封装了一些常用JS操作
Feb 25 PHP
解析php php_openssl.dll的作用
Jul 01 PHP
PHP自动生成后台导航网址的最佳方法
Aug 27 PHP
ThinkPHP3.1新特性之对Ajax的支持更加完善
Jun 19 PHP
兼容PHP和Java的des加密解密代码分享
Jun 26 PHP
PHP制作用户注册系统
Oct 23 PHP
开启PHP的伪静态模式
Dec 31 PHP
php实现对文件压缩简单的方法
Sep 29 PHP
PHP常用函数之base64图片上传功能详解
Oct 21 PHP
如何用PHP实现多线程编程
May 26 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引用地址改变变量值的问题
2012/03/23 PHP
php中time()与$_SERVER[REQUEST_TIME]用法区别
2014/11/19 PHP
php查看当前Session的ID实例
2015/03/16 PHP
Javascript中暂停功能的实现代码
2007/03/04 Javascript
Jquery 数组操作大全个人总结
2013/11/13 Javascript
jQuery 快速结束当前正在执行的动画
2013/11/20 Javascript
jquery实现鼠标拖动图片效果示例代码
2014/01/09 Javascript
使用JS取得焦点(focus)元素代码
2014/03/22 Javascript
js面向对象编程之如何实现方法重载
2014/07/02 Javascript
javascript匿名函数实例分析
2014/11/18 Javascript
JavaScript替换当前页面的方法
2015/04/03 Javascript
jQuery插件slider实现拖动滑块选取价格范围
2015/04/30 Javascript
jquery实现的动态回到顶部特效代码
2015/10/28 Javascript
JavaScript的模块化开发框架Sea.js上手指南
2016/05/12 Javascript
js实现自定义路由
2017/02/04 Javascript
layer弹出层中H5播放器全屏出错的解决方法
2017/02/21 Javascript
React.Js添加与删除onScroll事件的方法详解
2017/11/03 Javascript
详解vue 数组和对象渲染问题
2018/09/21 Javascript
JS实现的点击按钮图片上下滚动效果示例
2019/01/28 Javascript
vue实现弹幕功能
2019/10/25 Javascript
记录微信小程序 height: calc(xx - xx);无效问题
2019/12/30 Javascript
[05:26]2014DOTA2西雅图国际邀请赛 iG战队巡礼
2014/07/07 DOTA
Python实现约瑟夫环问题的方法
2016/05/03 Python
浅谈用Python实现一个大数据搜索引擎
2017/11/28 Python
Python实现字符串匹配算法代码示例
2017/12/05 Python
python中Apriori算法实现讲解
2017/12/10 Python
基于python list对象中嵌套元组使用sort时的排序方法
2018/04/18 Python
python 统计数组中元素出现次数并进行排序的实例
2018/07/02 Python
python 微信好友特征数据分析及可视化
2020/01/07 Python
python实现替换word中的关键文字(使用通配符)
2020/02/13 Python
日语翻译个人求职的自我评价
2013/10/14 职场文书
小学师德师风整改措施
2014/10/27 职场文书
优秀党支部申报材料
2014/12/24 职场文书
体育委员竞选稿
2015/11/21 职场文书
Spring boot应用启动后首次访问很慢的解决方案
2021/06/23 Java/Android
Python之matplotlib绘制饼图
2022/04/13 Python