Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last element of a matrix

Tags:

r

matrix

Consider I have following matrix

M <- matrix(1:9, 3, 3)
M
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9

I just want to find the last element i.e M[3, 3]

As this matrix column and row size are dynamic we can't hardcode it to M[3, 3]

How can I get the value of last element?

Currently I've done using the below code

M[nrow(M), ncol(M)]
# [1] 9

Is there any better way to do it?

like image 827
sag Avatar asked Jul 29 '15 11:07

sag


People also ask

How do I find the last element of an array?

1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.

How do you find the last element of a matrix in R?

then we can extract last value of M by using the command M[length(M)].

How do I find the last 5 elements of an array?

To get the last N elements of an array, call the slice method on the array, passing in -n as a parameter, e.g. arr. slice(-3) returns a new array containing the last 3 elements of the original array.

How do you find the last value of an object?

You can access the last value in an object directly, by using the Object. values() method to get an array of the object's values and calling the pop() method on the result, e.g. Object. values(obj). pop() .


2 Answers

A matrix in R is just a vector with a dim attribute, so you can just subset it as one

M[length(M)]
## [1] 9

Though (as mentioned by @James) your solution could be more general in case you want to keep you matrix structure, as you can add drop = FALSE

M[nrow(M), ncol(M), drop = FALSE]
#      [,1]
# [1,]    9

Though, my solution could be also modified in a similar manner using the dim<- replacement function

`dim<-`(M[length(M)], c(1,1))
#      [,1]
# [1,]    9

Some Benchmarks (contributed by @zx8754)

M <- matrix(runif(1000000),nrow=1000)

microbenchmark(
  nrow_ncol={
    M[nrow(M),ncol(M)]
  },
  dim12={
    M[dim(M)[1],dim(M)[2]]
  },
  length1={
    M[length(M)]
  },
  tail1={
    tail(c(M),1)
  },
  times = 1000
)

# Unit: nanoseconds
#      expr     min      lq        mean    median      uq      max neval cld
# nrow_ncol     605    1209    3799.908    3623.0    6038    27167  1000   a 
#     dim12     302     605    2333.241    1811.0    3623    19922  1000   a 
#   length1       0     303    2269.564    1510.5    3925    14792  1000   a 
#    tail 1 3103005 3320034 4022028.561 3377234.0 3467487 42777080  1000   b
like image 194
David Arenburg Avatar answered Oct 10 '22 17:10

David Arenburg


I would rather do:

tail(c(M),1)
# [1] 9
like image 2
Colonel Beauvel Avatar answered Oct 10 '22 16:10

Colonel Beauvel