您的位置:首页 > 编程语言 > Python开发

Python学习笔记(五)-实数/复数矩阵输出到txt文件(有格式选择)

2018-01-21 23:49 881 查看

1. 前言

当需要对计算过程进行记录时,一个可选的方案是将计算过程输出到txt文件中,无论是输出一个数,还是一个向量,还是一个矩阵,无非需要的是

文字说明
数据
输出格式

用file.write写入时,只能写入一个字符串,所以用现成的包比较好,自编OutTxt.py

2. 程序

# coding=UTF-8
# 保存为OutTxt.py
def Real(FilePath,Matrix,Fmt='w',**Option):
if 'width' in Option:
N = Option['width']
else:
N = 8
if 'string' in Option:
string = Option['string']
else:
string = '输出的矩阵:\n'
with open(FilePath,Fmt) as file:
NumR,NumC = Matrix.shape
file.write(string)
for i in range(NumR):
for j in range(NumC):
file.write(str(Matrix[i,j]).ljust(N+1)[0:N-1])
file.write(' ')
file.write('\n')
def Complex(FilePath,Matrix,Fmt='w',**Option):
if 'width' in Option:
N = Option['width']
else:
N = 8
if 'string' in Option:
string = Option['string']
else:
string = '输出的矩阵:\n'
RealM = Matrix.real
ImagM = Matrix.imag
# print(FilePath)
with open(FilePath,Fmt) as file:
NumR,NumC = Matrix.shape
file.write(string)
for i in range(NumR):
for j in range(NumC):
file.write(str(RealM[i,j]).ljust(N+1)[0:N-1])
file.write('+')
file.write('j'+str(ImagM[i,j]).ljust(N+1)[0:N-1])
file.write(' ')
file.write('\n')


3. 测试

#------将矩阵写入txt-------#
import OutTxt
import numpy as np
Z = np.random.rand(5,5)+np.random.rand(5,5)*1j
OutTxt.Complex('Complex.txt',Z,'w',string='My Matrix:\n',width=10)  # 实数矩阵
OutTxt.Real('Real.txt',Z.real,'w',string='My Matrix:\n',width=9)  # 复数矩阵

4. 结果
(也可对正负号进行讨论)
# complex.txt如下:
My Matrix:
0.5278015+j0.6348834 0.9629084+j0.1729091 0.9709622+j0.5446667 0.6142698+j0.8098638 0.7727490+j0.3458784
0.8532371+j0.0387547 0.3347495+j0.2680946 0.7926111+j0.9664751 0.3348781+j0.1489805 0.2930090+j0.0333537
0.3044924+j0.6159243 0.4662545+j0.4494182 0.2083607+j0.1815810 0.1977293+j0.7392929 0.3890427+j0.5362721
0.7181048+j0.1502132 0.3751771+j0.8522980 0.4731115+j0.2077804 0.4185118+j0.7511989 0.6989816+j0.4166925
0.1645633+j0.2876576 0.9031527+j0.2020653 0.3816732+j0.4030742 0.0616005+j0.3891945 0.2463344+j0.7085873

# Real.txt如下:
My Matrix:
0.527801 0.962908 0.970962 0.614269 0.772749
0.853237 0.334749 0.792611 0.334878 0.293009
0.304492 0.466254 0.208360 0.197729 0.389042
0.718104 0.375177 0.473111 0.418511 0.698981
0.164563 0.903152 0.381673 0.061600 0.246334


版权声明:本文为博主原创文章,未经博主允许不得转载。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: