# Program to calculate the trace of the given A without using loops
# in the R programming language.
# Created on: Oct 27, 2010
# Ankit Dangi, CMS 1010, ankit@cms.unipune.ac.in
# function to calculate the trace of the given matrix 'A'
# returns the trace of the matrix, if the given 'A' is a square matrix # else returns 'NA' trace <- function(A) { return (ifelse(is.square(A), sum(diag(A)), NA)); }
# function to check whether 'A' is a square matrix
# returns true, if the given 'A' is a matrix and if the # no. of rows and no. of cols of 'A' are equal; false, otherwise. is.square <- function(A) { return (is.matrix(A) && (nrow(A) == ncol(A))); }