Reputation: 199
I have written a function to store the diagonal elements of a matrix into a vector. but the output is not as I expected. The code is:
diagonal <- function(x) {
for (i in nrow(x)) {
for (j in ncol(x)) {
if (i == j) {
a <- x[i, j]
}
}
}
print(a)
}
I am passing a matrix to the function. What is wrong with the code?
Upvotes: 2
Views: 15077
Reputation: 887118
We can use the diag
function
diag(m1)
#[1] 1 5 9
Or
m1[col(m1)==row(m1)]
#[1] 1 5 9
If we are using the for
loop, we are looping by the sequence of rows and columns i.e 1:nrow(x)/1:ncol(x)
and not by nrow(x)/ncol(x)
.
diagonal <- function(x) {
a <- numeric(0)
for( i in 1:nrow(x)){
for(j in 1:ncol(x)){
if(i == j) {
a <- c(a, x[i,j])
}
}
}
a
}
diagonal(m1)
#[1] 1 5 9
m1 <- matrix(1:9, ncol=3)
Upvotes: 11