三阶矩阵运算库分享
By
jerryxjr1220
at 2021-12-19 • 0人收藏 • 844人看过
正好这几天要写一些关于三阶矩阵运算的小程序,需要用到一些基本的三阶矩阵的加减乘除。当然用python的numpy是非常方便的,但是如果仅仅只为了这一个小功能再去导入额外的包就太麻烦了,于是自己动手写了一下,顺便复习了一下线性代数,哈哈!
//Matrix三阶矩阵运算 namespace matrix add = function(x, y){ res = {{0,0,0};{0,0,0};{0,0,0}}; for i=1;3 { for j=1;3 { res[i][j] = x[i][j]+y[i][j]; } } return res; } minus = function(x, y){ res = {{0,0,0};{0,0,0};{0,0,0}}; for i=1;3 { for j=1;3 { res[i][j] = x[i][j]-y[i][j]; } } return res; } mult = function(x, y){ res = {{0,0,0};{0,0,0};{0,0,0}}; res[1][1] = x[1][1]*y[1][1] + x[1][2]*y[2][1] + x[1][3]*y[3][1]; res[1][2] = x[1][1]*y[1][2] + x[1][2]*y[2][2] + x[1][3]*y[3][2]; res[1][3] = x[1][1]*y[1][3] + x[1][2]*y[2][3] + x[1][3]*y[3][3]; res[2][1] = x[2][1]*y[1][1] + x[2][2]*y[2][1] + x[2][3]*y[3][1]; res[2][2] = x[2][1]*y[1][2] + x[2][2]*y[2][2] + x[2][3]*y[3][2]; res[2][3] = x[2][1]*y[1][3] + x[2][2]*y[2][3] + x[2][3]*y[3][3]; res[3][1] = x[3][1]*y[1][1] + x[3][2]*y[2][1] + x[3][3]*y[3][1]; res[3][2] = x[3][1]*y[1][2] + x[3][2]*y[2][2] + x[3][3]*y[3][2]; res[3][3] = x[3][1]*y[1][3] + x[3][2]*y[2][3] + x[3][3]*y[3][3]; return res; } det = function(x){ return x[1][1]*x[2][2]*x[3][3] + x[1][2]*x[2][3]*x[3][1] + x[1][3]*x[2][1]*x[3][2] - x[3][1]*x[2][2]*x[1][3] - x[3][2]*x[2][3]*x[1][1] - x[3][3]*x[2][1]*x[1][2]; } star = function(x){ res = {{0,0,0};{0,0,0};{0,0,0}}; res[1][1] = x[2][2]*x[3][3]-x[3][2]*x[2][3]; res[1][2] = x[3][2]*x[1][3]-x[1][2]*x[3][3]; res[1][3] = x[1][2]*x[2][3]-x[2][2]*x[1][3]; res[2][1] = x[2][3]*x[3][1]-x[3][3]*x[2][1]; res[2][2] = x[3][3]*x[1][1]-x[1][3]*x[3][1]; res[2][3] = x[1][3]*x[2][1]-x[2][3]*x[1][1]; res[3][1] = x[2][1]*x[3][2]-x[3][1]*x[2][2]; res[3][2] = x[3][1]*x[1][2]-x[1][1]*x[3][2]; res[3][3] = x[1][1]*x[2][2]-x[2][1]*x[1][2]; return res; } reverse = function(x){ d = det(x); new = star(x); for i=1;3 { for j=1;3 { new[i][j] = new[i][j]/d; } } return new; }
调用
import console; import matrix; x = {{1,2,3},{4,5,6},{7,8,9}}; y = {{1,3,5},{7,9,2},{4,6,8}}; console.dump(matrix.mult(x, matrix.reverse(y))) console.pause(true);
和python的numpy对比
3 个回复 | 最后更新于 2021-12-21
登录后方可回帖
点赞