是否有一个函数可以使用基函数证明矩阵是否为方阵?
is there a function that can prove if a matrix is square using the base functions?
#完成模板中的代码块以编写一个接受矩阵(任意大小)M 作为参数的函数,returns 如果矩阵为正方形则为 TRUE,否则为 FALSE。它也应该适用于标量。
#我给出了第一部分代码:
```{r}
is.square <- 函数(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 "}"
我认为你在这行中有错字
(dim(M)[1]) != dim(M)[2])
应该是
(dim(M)[1] != dim(M)[2])
#完成模板中的代码块以编写一个接受矩阵(任意大小)M 作为参数的函数,returns 如果矩阵为正方形则为 TRUE,否则为 FALSE。它也应该适用于标量。
#我给出了第一部分代码:
```{r}
is.square <- 函数(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 "}"
我认为你在这行中有错字
(dim(M)[1]) != dim(M)[2])
应该是
(dim(M)[1] != dim(M)[2])