Python學習筆記(五)-實數/複數矩陣輸出到txt文件(有格式選擇)

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 
版權聲明:本文爲博主原創文章,未經博主允許不得轉載。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章