1. 程式人生 > 程式設計 >jupyter notebook中美觀顯示矩陣例項

jupyter notebook中美觀顯示矩陣例項

我就廢話不多說了,還是直接看程式碼吧!

from IPython.display import display,Latex,Math
%matplotlib inline
 
from IPython.core.interactiveshell import InteractiveShell
sh = InteractiveShell.instance()
 
def number_to_str(n,cut=5):
  ns=str(n)
  format_='{0:.'+str(cut)+'f}'
  if 'e' in ns or ('.' in ns and len(ns)>cut+1):
    return format_.format(n)
  else:
    return str(n)
 
def matrix_to_latex(mat,style='bmatrix'):
  if type(mat)==np.matrixlib.defmatrix.matrix:
    mat=mat.A
  head=r'\begin{'+style+'}'
  tail=r'\end{'+style+'}'
  if len(mat.shape)==1:
    body=r'\\'.join([str(el) for el in mat])
    return head+body+tail
  elif len(mat.shape)==2:
    lines=[]
    for row in mat:
      lines.append('&'.join([number_to_str(el) for el in row])+r'\\')
    s=head+' '.join(lines)+tail
    return s
  return None
 
sh.display_formatter.formatters['text/latex'].type_printers[np.ndarray]=matrix_to_latex

輸入後執行即可

我們在進行矩陣列印的時候就相當美觀咯!!!

jupyter notebook中美觀顯示矩陣例項

補充知識:解決python numpy 大陣列顯示不全的問題

import numpy as np
np.set_printoptions(threshold=np.inf)

或者

np.set_printoptions(threshold='nan')

其中threshold表示:

Total number of array elements to be print(輸出陣列的元素數目)

以上這篇jupyter notebook中美觀顯示矩陣例項就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。