In Matlab, how do I compare two container.Map objects by element?

I have two container.Map objects with identical keys and values. Is there a Matlab function that will return true in the following scenario:

>> m1 = containers.Map('hi', 'ho');
>> m2 = containers.Map('hi', 'ho');
>> m1 == m2

ans =

     0

      

+3


source to share


2 answers


isequal

your friend is here ...

Through isequal

When comparing handle objects, use EQ or the == operator to test
whether objects are the same handle. Use isequal to test if objects
have equal property values, even if those objects are different
handles.

      



and as @gire mentioned is containers.Map

related to the classhandle

So, considering simple cards

isequal(m1,m2)

ans =

     1

      

0


source


The class containers.Map

inherits from the handle class, which means that the operator ==

will return true only in the following case:

m1 = containers.Map('hi', 'ho');
m2 = m1;
m2 == m1

      

The pens behave like a pointer (to some extent!).



If you want to compare two different cards, you need to loop through their elements and compare them one at a time. For example:

keys1 = m1.keys;
keys2 = m2.keys;

% // If the keys are not equal there is no reason to loop
if ~isequal(keys1, keys2)
    disp('Maps are not equal');
    return;
end

% // Since at this point it is known that keys1 == keys2, keys1 is used as a
% // base
results = false(size(keys1));
for i = 1:length(keys1)
    results(i) = ms1(keys{i}) == ms2(keys{i});
end

if all(results)
    disp(';aps are equal');
else
    disp('Maps are not equal');
end

      

+1


source







All Articles