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
标签:对称矩阵
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python使用openCV遍历文件夹里所有视频文件并保存成图片
2023-05-30 18:14:22
![](https://img.aspxhome.com/file/2023/6/103186_0s.png)
个人从事设计行业40句观感
2008-04-07 13:58:00
![](https://img.aspxhome.com/file/UploadPic/20084/7/2008471415284s.jpg)
python算法与数据结构之单链表的实现代码
2022-09-30 14:35:39
![](https://img.aspxhome.com/file/2023/0/98820_0s.png)
python引入导入自定义模块和外部文件的实例
2023-01-25 10:02:18
python实现百度关键词排名查询
2023-01-19 12:26:58
linux下安装php扩展memcache的方法
2023-11-21 19:49:02
![](https://img.aspxhome.com/file/2023/4/112714_0s.jpg)
python多进程实现文件下载传输功能
2022-06-27 02:22:41
python 中 .py文件 转 .pyd文件的操作
2022-02-17 09:59:38
![](https://img.aspxhome.com/file/2023/8/107458_0s.jpg)
基于Python实现下载网易音乐代码实例
2023-05-25 01:05:51
![](https://img.aspxhome.com/file/2023/0/105420_0s.png)
Python中定时任务框架APScheduler的快速入门指南
2021-07-16 02:51:21
宽屏不是用来阅读的
2009-04-05 15:59:00
Windows64x下VScode下载过程
2021-03-08 20:10:47
![](https://img.aspxhome.com/file/2023/1/81441_0s.jpg)
Python实现学生信息管理系统的示例代码
2022-12-06 22:17:56
![](https://img.aspxhome.com/file/2023/8/83918_0s.png)
PHP完全二叉树定义与实现方法示例
2023-07-04 10:49:10
![](https://img.aspxhome.com/file/2023/8/55378_0s.jpg)
Pytorch中的 torch.distributions库详解
2021-05-17 22:26:47
![](https://img.aspxhome.com/file/2023/1/84081_0s.png)
利用Python在一个文件的头部插入数据的实例
2023-02-06 13:04:33
Python标准库os.path包、glob包使用实例
2021-09-04 13:49:03
Python for Informatics 第11章之正则表达式(四)
2023-06-15 04:48:39
适合所有表的添加、删除、修改的函数
2008-04-15 15:29:00
SQL Server数据库服务器高性能设置
2010-11-25 16:00:00