雖然是用於跟蹤矩陣的功能,如下圖所示:使用什麼功能對於跟蹤矩陣R中
sum(diag(matrix))
這可能會錯誤地給你一個結果,如果矩陣不是廣場(即「N×N的「大小)。是否有任何其他內置函數用於運行矩陣的「跟蹤」?
雖然是用於跟蹤矩陣的功能,如下圖所示:使用什麼功能對於跟蹤矩陣R中
sum(diag(matrix))
這可能會錯誤地給你一個結果,如果矩陣不是廣場(即「N×N的「大小)。是否有任何其他內置函數用於運行矩陣的「跟蹤」?
下面是一個快速函數,用於測試對象是否爲矩陣,然後測試它是否也是方形。
tr <- function (m)
{
total_sum <- 0
if(is.matrix(m))
{
row_count <- nrow(m)
col_count <- ncol(m)
if(row_count == col_count)
{
total_sum <-sum(diag(m))
total_sum
}
else
{
message ('Matrix is not square')
}
}
else
{
message('Object is not a matrix')
}
}
我還發現了以下包Matrix.Trace:
您可以嘗試使用特徵值
# first find eigenvalues e = eigen(matrix) # Calculate the trace of the matrix, and compare with the sum of the eigenvalues. # function to calculate the trace using sum of the diagonal trace <- function(data)sum(diag(data)) trace(H) # using sum of the eigenvalues sum(e$values)
希望它能幫助。
不要在大矩陣上試試這個。 –
正如您所指出的那樣,'matrixcalc'包有一個'matrix.trace'函數。您可以在控制檯中輸入「matrix.trace」來查看功能代碼。 – eipi10