Clear Filters
Clear Filters

Comparing two Matrix for similar elements

6 views (last 30 days)
suppose you run a check between two matrix, like c=0; if A(1,1) == B (1, 1:3) c=c+1; else c=0; end and the output(ans) is (true, true, false) , I mean (1 1 0).
my counter(c) should run twice(if if A(1,1), B(1,1) and B(1,2) is equal to 8) but it will show c=0. I need C = 2
Other way I found is - Count only when it is true, like
if A(1,1) == B(1,1) c=c+1; else c=0; end
but in the second case, i have to do it for all B elements, and that's not good for big matrix. how to check and count?
  2 Comments
Andrei Bobrov
Andrei Bobrov on 24 May 2017
Please attach your matrices A and B storing in mat - file.
Jan
Jan on 24 May 2017
The question is not clear:
c=0;
if A(1,1) == B (1, 1:3)
c=c+1;
else
c=0;
end
Note that A(1,1) == B (1, 1:3) replies a vector, but if requires a scalar condition. Therefore Matlab inserts an all() implicitely.
and the output(ans) is (true, true, false) , I mean (1 1 0).
The shown code does not have any output. It replies either c=1 or c=0, but not [1,1,0].
my counter(c) should run twice(if if A(1,1), B(1,1) and B(1,2)
is equal to 8)
I cannot folow you here.

Sign in to comment.

Answers (2)

Andrei Bobrov
Andrei Bobrov on 24 May 2017
Edited: Andrei Bobrov on 24 May 2017
c = nnz(A(:)' == B(:)); % MATLAB >= R2016b
c = nnz(bsxfun(@eq, A(:)', B(:))); % MATLAB <= R2016a
  3 Comments
Walter Roberson
Walter Roberson on 6 Dec 2019
Only in the sense that some objects cannot be compared. For example if A is object class tf (transfer function) and B is object class primitive chart line, then you would get an error message. But the code would be fine with A being double and B being character for example.
The original question implied that the array sizes are not the same, so the code should not be checking that they are the same.
Daniel Brower
Daniel Brower on 6 Dec 2019
I mean if A is an nxn matrix of real numbers and B is an nxn matrix of real numbers, how would I check if A and B are similar matrices to each other, in the sense that B=S^-1*A*S.

Sign in to comment.


Jan
Jan on 24 May 2017
Edited: Jan on 24 May 2017
Does only A(1,1) occur in your porblem? Then:
c = (A(1,1) == B)
or if the number of equal elements is wanted
c = sum(A(1,1) == B) % or nnz() instead of sum()
If all elements of A are concerned, see either Andrei's solution, or:
c = sum(ismember(A(:), B(:)) % Or B(:), A(:) ?
  2 Comments
Zeina Abdullah
Zeina Abdullah on 5 Jan 2022
@Jan can you help me by answer my question in my profile please . i am tring to find similar problem but I did not find
Walter Roberson
Walter Roberson on 6 Jan 2022
https://www.mathworks.com/matlabcentral/answers/1623080-how-to-find-relationship-between-two-or-more-matrix?s_tid=srchtitle appears to be the reference

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!