正常情況下揉抵,矩陣的存儲(chǔ)需要消耗n*n個(gè)存儲(chǔ)單元,而對稱存儲(chǔ)只需要n×(n+1)/2個(gè)存儲(chǔ)單元品洛。當(dāng)n較大時(shí)囱怕,節(jié)省下的存儲(chǔ)單元十分可觀。
借助numpy生成矩陣毫别,在python中的實(shí)現(xiàn)代碼:
import numpy as np
# 矩陣的階數(shù)
N = 5
def get_matrix():
"""
創(chuàng)建一個(gè)5x5的隨機(jī)整數(shù)矩陣
:return:
"""
return np.random.randint(1, 5, size=(N, N))
def tri(matrix, method="low"):
"""
保留矩陣的上三角或下三角
:param matrix:
:param method:
:return:
"""
return np.tril(matrix) if method == "low" else np.triu(matrix)
def diag(matrix):
"""
生成對稱矩陣
:param matrix:
:return:
"""
return matrix + matrix.T - np.diag(matrix.diagonal())
def init_list():
"""
根據(jù)矩陣維度生成一個(gè)一維數(shù)組存儲(chǔ)對稱矩陣數(shù)據(jù)
:return:
"""
return [0] * (int((N + 1) * N / 2))
def get_index(x, y):
"""
根據(jù)x,y獲取對應(yīng)列表中的索引, 計(jì)算公式為: x>=y時(shí) x(x+1)/2 + y, x<y時(shí) y(y+1)/2 + x
:param x:
:param y:
:return:
"""
if x >= y:
return x * (x + 1) // 2 + y
return y * (y + 1) // 2 + x
def save_to_list(index_array, r_list, r_mt):
"""
將數(shù)據(jù)存儲(chǔ)到一維數(shù)組中
:param index_array:
:param r_list:
:param r_mt:
:return:
"""
for index in range(len(r_list)):
x, y = index_array[1][index], index_array[0][index]
r_list[get_index(x, y)] = r_mt[y][x]
return r_list
def list_to_matrix(r_list):
"""
將數(shù)組還原為對稱矩陣
:param r_list:
:return:
"""
new_matrix = np.zeros((N, N), dtype=int)
new_matrix_index = np.where(new_matrix == 0)
for index in range(len(new_matrix_index[0])):
x, y = new_matrix_index[1][index], new_matrix_index[0][index]
new_matrix[y, x] = r_list[get_index(x, y)]
return new_matrix
if __name__ == '__main__':
mt = get_matrix()
low_mt = tri(mt)
diag_mt = diag(low_mt)
print("生成的對稱矩陣為:\n%s" % diag_mt)
low_diag_mt = tri(diag_mt)
print("保留下三角的矩陣數(shù)據(jù): \n%s" % low_diag_mt)
no_zero_index = np.nonzero(low_diag_mt)
i_list = init_list()
print("根據(jù)維度初始化的數(shù)組長度為: \n%s" % len(i_list))
res_list = save_to_list(no_zero_index, i_list, low_diag_mt)
print("存儲(chǔ)后的數(shù)組為:\n%s" % res_list)
res_matrix = list_to_matrix(res_list)
print("還原后的對稱矩陣為: \n %s" % res_matrix)
運(yùn)行結(jié)果: