Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
给定一个方阵M,如何求对角线上的元素之和?一定有比这更简单的方法:
M
sum(sum(diag(diag(M), 0)))
实际上,我正在寻找的是踪迹:
1> M = reshape(1:9, 3, 3) M = 1 4 7 2 5 8 3 6 9 2> trace(M) ans = 15
似乎sum(diag(M))工作正常。
sum(diag(M))
1> M = reshape(1:9, 3, 3) M = 1 4 7 2 5 8 3 6 9 2> sum(diag(M)) ans = 15