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

发布时间 - 2026-01-11 01:29:27    点击率:

本文实例讲述了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, '+'));
?>

PS:这里再为大家推荐几款在线计算工具供大家参考使用:

在线一元函数(方程)求解计算工具:
http://tools./jisuanqi/equ_jisuanqi

科学计算器在线使用_高级计算器在线计算:
http://tools./jisuanqi/jsqkexue

在线计算器_标准计算器:
http://tools./jisuanqi/jsq

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP数学运算技巧总结》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP常用遍历算法与技巧总结》、《PHP数据结构与算法教程》、《php程序设计算法总结》、《php正则表达式用法总结》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。


# PHP  # 数组  # 矩阵  # 数学运算  # PHP简单实现二维数组的矩阵转置操作示例  # PHP实现图的邻接矩阵表示及几种简单遍历算法分析  # PHP实现蛇形矩阵  # 回环矩阵及数字螺旋矩阵的方法分析  # PHP 数组和字符串互相转换实现方法  # PHP中数组合并的两种方法及区别介绍  # PHP遍历数组的方法汇总  # PHP遍历数组的几种方法  # php数组函数序列之array_keys() - 获取数组键名  # php获取数组中重复数据的两种方法  # PHP实现顺时针打印矩阵(螺旋矩阵)的方法示例  # 程序设计  # 操作技巧  # 相关内容  # 遍历  # 感兴趣  # 数据结构  # 给大家  # 更多关于  # 所述  # 几款  # 再为  # 运算符  # 讲述了  # 正则表达式  # Ensure  # identical  # cols  # isset  # calculate  # is_numeric 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 手机怎么制作网站教程步骤,手机怎么做自己的网页链接?  高端建站如何打造兼具美学与转化的品牌官网?  瓜子二手车官方网站在线入口 瓜子二手车网页版官网通道入口  电商网站制作多少钱一个,电子商务公司的网站制作费用计入什么科目?  HTML透明颜色代码怎么让图片透明_给img元素加透明色的技巧【方法】  实现点击下箭头变上箭头来回切换的两种方法【推荐】  详解一款开源免费的.NET文档操作组件DocX(.NET组件介绍之一)  如何快速启动建站代理加盟业务?  Laravel怎么使用Collection集合方法_Laravel数组操作高级函数pluck与map【手册】  如何快速选择适合个人网站的云服务器配置?  如何彻底删除建站之星生成的Banner?  Python3.6正式版新特性预览  如何自定义建站之星模板颜色并下载新样式?  大连企业网站制作公司,大连2025企业社保缴费网上缴费流程?  Laravel任务队列怎么用_Laravel Queues异步处理任务提升应用性能  Midjourney怎么调整光影效果_Midjourney光影调整方法【指南】  今日头条AI怎样推荐抢票工具_今日头条AI抢票工具推荐算法与筛选【技巧】  Win11应用商店下载慢怎么办 Win11更改DNS提速下载【修复】  使用C语言编写圣诞表白程序  轻松掌握MySQL函数中的last_insert_id()  如何快速重置建站主机并恢复默认配置?  php结合redis实现高并发下的抢购、秒杀功能的实例  宙斯浏览器怎么屏蔽图片浏览 节省手机流量使用设置方法  佛山企业网站制作公司有哪些,沟通100网上服务官网?  js实现获取鼠标当前的位置  Laravel如何配置Horizon来管理队列?(安装和使用)  Laravel如何使用Gate和Policy进行授权?(权限控制)  linux top下的 minerd 木马清除方法  javascript中数组(Array)对象和字符串(String)对象的常用方法总结  PHP的CURL方法curl_setopt()函数案例介绍(抓取网页,POST数据)  JavaScript如何操作视频_媒体API怎么控制播放  晋江文学城电脑版官网 晋江文学城网页版直接进入  Laravel如何使用Blade模板引擎?(完整语法和示例)  Microsoft Edge如何解决网页加载问题 Edge浏览器加载问题修复  详解Android图表 MPAndroidChart折线图  简单实现Android验证码  免费的流程图制作网站有哪些,2025年教师初级职称申报网上流程?  Laravel怎么调用外部API_Laravel Http Client客户端使用  Laravel怎么写单元测试_PHPUnit在Laravel项目中的基础测试入门  Laravel如何实现图片防盗链功能_Laravel中间件验证Referer来源请求【方案】  ChatGPT怎么生成Excel公式_ChatGPT公式生成方法【指南】  Laravel如何配置.env文件管理环境变量_Laravel环境变量使用与安全管理  Laravel如何使用Eloquent ORM进行数据库操作?(CRUD示例)  简单实现Android文件上传  JavaScript中的标签模板是什么_它如何扩展字符串功能  重庆市网站制作公司,重庆招聘网站哪个好?  INTERNET浏览器怎样恢复关闭标签页_INTERNET浏览器标签恢复快捷键与方法【指南】  Laravel怎么实现微信登录_Laravel Socialite第三方登录集成  Laravel如何获取当前登录用户信息_Laravel Auth门面使用与Session用户读取【技巧】  米侠浏览器网页背景异常怎么办 米侠显示修复