You are on page 1of 1

File: /home/dangiankit/Desktop/cms-…it-dangi-cms-1010-ir-asg-1/3.

r Page 1 of 1

# 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)));
}

You might also like