python实现由数组生成对称矩阵
作者:快到皖里来 发布时间:2022-12-09 15:01:53
标签:对称矩阵
在实际应用中,经常会遇上这样的小需求:根据一段给定的数组,生成由这一段数组值构成的对称矩阵。
例如,给定数组[1,2,3,4,5,6,7,8,9,10],要求生成如下的矩阵:
[[0,1,2,3,4],
[1,0,5,6,7],
[2,5,0,8,9],
[3,6,8,0,10],
[4,7,9,10,0]]
其中,对角元全为0,该类型的矩阵完全由给定的数组决定。
笔者给出实现以上功能的一种python参考代码如下:
def semi_to_full(m):
import numpy as np
n = len(m)
n_matrix = int((1+int((1+8*n)**0.5))/2)
semi_matrix = np.zeros((n_matrix,n_matrix),dtype='int32')
start_index = 0
for row in range(n_matrix-1):
end_index = start_index+(n_matrix-1-row)
semi_matrix[row,row+1:]=m[start_index:end_index]
start_index = end_index
full_matrix = semi_matrix+semi_matrix.T
return full_matrix
代码逻辑如此:先得到数组长度以推定出所欲生成矩阵的规格,接着按照数组值的顺序生成矩阵的上对角元,最后利用对称性完成整个矩阵输出。
该函数参数只有一个,即给定的numpy数组。
来源:https://www.cnblogs.com/pythonfl/p/14730971.html
0
投稿
猜你喜欢
- 前言上机实践课程开始了,嗯,老师来了之后念了下PPT,然后说:开始做吧.........然后就开始了Python的GUI之路,以前没接触过P
- 1、视图函数之前的文章说过,在 Flask 中路由是请求的 url 与处理函数之间的映射,使用app.route装饰器将处理函数和 url
- 字符串格式化输出是python非常重要的基础语法,今天就把三种格式化输出做一个简单的总结,希望对大家有帮助。格式化输出:内容按照一定格式要求
- 列表的格式:变量A的类型为列表 namesList = ['xiaoWang','xiaoZhang',
- 一、网络结构的可视化我们训练神经网络时,除了随着step或者epoch观察损失函数的走势,从而建立对目前网络优化的基本认知外,也可以通过一些
- 用Django开发网站的时候,前端页面内的文本框总是不能被设置为只读,找了一些资料发现可以在form class里面进行设置。方法一:首先在
- 一、备份数据库 1、打开SQL企业管理器,在控制台根目录中依次点开Microsoft SQL Server
- 连接查询:是将两个查询(或表)的每一行,以“两两横同对接”的方式,所得到的所有行的结果,即一个表中的某行,跟另一个表中的某行。进行“横向对接
- 最近闲来无事, 于是就简单学习了下Go语言的基本的用法。由于实践才是最快的学习方法,所以这里就以下载网络图片或文件入手来学习Go语言文件下载
- 相信很多小伙伴想着自己的移动端项目能够自动转换为rem,这才符合前端的潮流,如果用自己手写或者编辑器插件来改动十分不方便还容易出错,我在网上
- IE独有属性AlphaImageLoader用于修正7.0以下版本中显示PNG图片的半透明效果。这个滤镜的问题在于浏览器加载图片时它会终止内
- 本文介绍了详解TensorFlow在windows上安装与简单示例,分享给大家,具体如下:安装说明平台:目前可在Ubuntu、Mac OS、
- mysql中replace函数替换字符串介绍下mysql的REPLACE()函数语法:REPLACE()函数的语法如下:REPLACE(st
- 1、建表语句:CREATE TABLE `employees` ( `emp_no` int(11) NOT NULL, `birth_da
- 前言我自己常用的简单Python代码调试工具是IDLE和Sublime3,IDLE很少使用了,基本上用Sublime3稍微多一些,Subli
- 想学习Python的人都会有一个困惑,那就是Python目前有两个版本Python2和Python3,Python2与Python3有何区别
- 一、查看可用字体import pygameprint(pygame.font.get_fonts())二、设置字体1.使用系统字体self.
- 本文实例讲述了js实现黑色简易的滑动门网页tab选项卡效果。分享给大家供大家参考。具体如下:这是一款js实现的黑色风格网页滑动门菜单,虽然简
- 我用 ip=Request.ServerVariables
- 大家都知道搜索引擎比较喜欢H1。在SEO中H1也是很基础也很重要的一步。但有些时候为了界面风格的原因,很多标题性的文字做成了图片。大多数情况