0

I want to compare two matrices

  A B C
A 1 1 0
B 0 1 -1
C 1 0 0
  A B C
A 1 -1 0
B 0 -1 -1
C 1 0 1

So that output should be

  A B C
A 0 -1 0
B 0 -1 0
C 0 0 1

Values for which matrix 1 == matrix 2 will be 0 and for which matrix1 != matrix2 the value of matrix2 will be assigned.

user3253470
  • 191
  • 1
  • 4
  • 11

1 Answers1

3

You can do a "term by term" comparison with mat1==mat2 and then put the number you want according to the result: if mat1 and mat2 are your matrices:

> ifelse(mat1==mat2, 0, mat2)
   #   A  B C
   # A 0 -1 0
   # B 0 -1 0
   # C 0  0 1

EDIT based on the comments
If you also want to know which percentage of values were not equal, you can do:

eq <- mat1==mat2 # avoid to later compute this twice
ifelse(eq, 0, mat2) # get the desired matrix
round(sum(!eq)/length(eq)*100, 2) # get the percentage of non equal values
#[1] 33.33
Cath
  • 23,906
  • 5
  • 52
  • 86
  • In row A and B of the resulting matrix, the value is -1 because in 'mat2' the value was changed by '-1'. Whereas, in row C the last value should be '1' not '-1' because the corresponding value in mat1 (0) is replaced by (1) in mat2. – user3253470 Oct 01 '15 at 10:52
  • 2
    @user3253470 If this works, then you can accept the answer by [clicking the checkmark](http://stackoverflow.com/help/someone-answers) at the left of the answer. – Jaap Oct 01 '15 at 11:03
  • Is it possible to apply some scoring function on this. Some function which represents how much different the compared matrices are? for example a percentage or so.. – user3253470 Oct 01 '15 at 11:04
  • I don't think this is the solution. Let me explain again. For example in above example there were total 3 replacements. so among 9 values of M1 and M2 3 values has been changed in resulting matrix, so percentage of change will be 33.33%. I mean a calculation like this. – user3253470 Oct 01 '15 at 11:10
  • 1
    @user3253470 so probably `sum(mat1!=mat2)/length(mat2)*100` – Cath Oct 01 '15 at 11:13
  • Thanks. Can you please tell me how I should deal the cases where dimension of matrices to compared are not same? In such cases I am getting "non-conformable arrays" error message – user3253470 Oct 01 '15 at 11:48
  • @user3253470 how can you check if 2 matrices are the same "element-wise" if they haven't the same dimension: how do you make the element "match" ? (ie how do you know which element to use for your comparison?) – Cath Oct 01 '15 at 11:57
  • 1
    @user3253470 it not a good practice to extend your problem statement in the same question. If you think CathG answer solves your problem you should accept it and ask your another question separately. – Dhawal Kapil Oct 01 '15 at 11:57
  • @Cath Can you please suggest the answer for this question: [http://stackoverflow.com/questions/36420909/compare-matrices-to-find-the-differences] – user3253470 Apr 05 '16 at 08:30