- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to check if two matrices are equal in R?
When we matrices of larger size and the data is expected to from the same distribution or from same sources then we might expect that the matrices are equal. In this type of situations, we would like to check whether the two matrices are equal or not. This can be done with the help of all.equal function as shown in the below examples.
Example
M1<-matrix(1:100,ncol=10) M1
Output
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 11 21 31 41 51 61 71 81 91 [2,] 2 12 22 32 42 52 62 72 82 92 [3,] 3 13 23 33 43 53 63 73 83 93 [4,] 4 14 24 34 44 54 64 74 84 94 [5,] 5 15 25 35 45 55 65 75 86 96 [7,] 7 17 27 37 47 57 67 77 87 97 [8,] 8 18 28 38 48 58 68 78 88 98 [9,] 9 19 29 39 49 59 69 79 89 99 [10,] 10 20 30 40 50 60 70 80 90 100
Example
M2<-matrix(1:100,ncol=10) M2
Output
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 11 21 31 41 51 61 71 81 91 [2,] 2 12 22 32 42 52 62 72 82 92 [3,] 3 13 23 33 43 53 63 73 83 93 [4,] 4 14 24 34 44 54 64 74 84 94 [5,] 5 15 25 35 45 55 65 75 85 95 [6,] 6 16 26 36 46 56 66 76 86 96 [7,] 7 17 27 37 47 57 67 77 87 97 [8,] 8 18 28 38 48 58 68 78 88 98 [9,] 9 19 29 39 49 59 69 79 89 99 [10,] 10 20 30 40 50 60 70 80 90 100
all.equal(M1,M2)
[1] TRUE
Example
M3<-matrix(rpois(64,10),nrow=8) M3
Output
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 8 7 7 9 11 13 8 9 [2,] 9 9 9 11 8 10 9 8 [3,] 7 8 9 12 15 11 9 8 [4,] 11 10 15 11 11 11 10 14 [5,] 14 13 14 8 12 12 2 16 [6,] 7 12 6 10 3 5 9 12 [7,] 13 7 15 10 4 7 8 8 [8,] 6 13 7 9 11 12 13 7
Example
M4<-matrix(rpois(64,10),nrow=8) M4
Output
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 11 10 9 5 14 4 8 13 [2,] 12 9 15 10 11 11 11 14 [3,] 5 12 12 12 7 20 13 11 [4,] 4 12 16 17 13 9 8 14 [5,] 11 17 13 14 10 6 16 12 [6,] 14 11 8 16 10 12 7 11 [7,] 10 10 8 10 6 12 8 12 [8,] 7 15 8 10 5 11 11 5
all.equal(M3,M4)
[1] "Mean relative difference: 0.3885918"
Example
M5<-matrix(rpois(40,5),nrow=20) M5
Output
[,1] [,2] [1,] 2 12 [2,] 5 3 [3,] 8 4 [4,] 8 7 [5,] 10 9 [6,] 7 10 [7,] 3 4 [8,] 5 9 [9,] 7 5 [10,] 2 1 [11,] 3 11 [12,] 3 5 [13,] 4 3 [14,] 9 3 [15,] 2 7 [16,] 8 9 [17,] 2 9 [18,] 7 3 [19,] 0 7 [20,] 5 6
Example
M6<-matrix(rpois(40,5),nrow=20) M6
Output
[,1] [,2] [1,] 2 8 [2,] 6 9 [3,] 4 7 [4,] 1 2 [5,] 3 3 [6,] 2 4 [7,] 4 7 [8,] 6 6 [9,] 5 5 [10,] 3 1 [11,] 7 6 [12,] 6 6 [13,] 2 4 [14,] 7 3 [15,] 7 4 [16,] 4 4 [17,] 4 3 [18,] 3 4 [19,] 10 6 [20,] 4 6
all.equal(M5,M6)
[1] "Mean relative difference: 0.5952381"
Advertisements