Home > OS >  is there a function that can prove if a matrix is square using the base functions?
is there a function that can prove if a matrix is square using the base functions?

Time:05-03

#Complete the code chunk in the template to write a function that accepts a matrix (of any size) M as an argument and returns TRUE if the matrix is square and FALSE otherwise. It should work for scalars as well.

#I am given the first part of the code:

```{r}

is.square <- function(M) {

}


#and I am required to finish the code so that it gives "TRUE" OR "FALSE" when I test the code on these examples: 

#a=2
# is.square(a)
#
# A = matrix(1:4,nrow=2,ncol=2) # is.square(A)
#
# B = matrix(1:9,nrow=3,ncol=3) # is.square(B)
#
# C = matrix(1:6,nrow=3,ncol=2) # is.square(C)


#only base functions are allowed and no matter what I try I cannot get it right. 

#I've tried 

    is.square <- function(M) {
  
  if(dim(M)[1]) != dim(M)[2]) {
    
    return(FALSE)
    
  } else {
    
    return(TRUE)
  }

}


#but get the errors 
> is.square <- function(M) {
    
    if(dim(M)[1]) != dim(M)[2]) {
Error: unexpected '!=' in:
"  
  if(dim(M)[1]) !="
>     
>     return(FALSE)
Error: no function to return from, jumping to top level
>     
>   } else {
Error: unexpected '}' in "  }"
>     
>     return(TRUE)
Error: no function to return from, jumping to top level
>   }
Error: unexpected '}' in "  }"
> 
> }
Error: unexpected '}' in "}"

CodePudding user response:

I think you had a typo in the line

(dim(M)[1]) != dim(M)[2])

which is supposed to be

(dim(M)[1] != dim(M)[2])
  • Related