Finding sum of all elements in matrixA using inbuilt functions

##### Title

##### Question

startTime <- Sys.time()

totalsum <- 0

for (i in 1:3) {

for (j in 1:3) {

totalsum <- totalsum+matrixA[i,j]

}

}

print(totalsum)

[1] 237

endTime <- Sys.time()

endTime- startTime

startTime <- Sys.time()

sum(matrixA)

[1] 237

endTime <- Sys.time()

endTime- startTime

totalsum <- 0

for (i in 1:3) {

for (j in 1:3) {

totalsum <- totalsum+matrixA[i,j]

}

}

print(totalsum)

[1] 237

endTime <- Sys.time()

endTime- startTime

**Time difference of 0.008000851 secs**startTime <- Sys.time()

sum(matrixA)

[1] 237

endTime <- Sys.time()

endTime- startTime

**Time difference of 0 secs**

**Sir the above time difference is ok**

R Operations-on-Matrices-and-Data-Frames 08-09 min 20-30 sec

__Answers:__

Yes. You might want to observe that the time taken to calculate the sum using the inbuilt function is less than that calculated using a forloop.

17-05-20, 10:05 a.m.AlamuLogin to add comment