Overloading Equality Operator for Arrays

I have a class with the eq() operator overloaded, but I'm not sure the best way to make it work with object arrays, in a similar way to the way standard arrays work for equality. Here's the code that I have right now. For reference, the class is designed to work with spheres in 3D space, with a center [x, y, z] and a radius.
function test=eq(a,b)
if all(size(a.xyz)==size(b.xyz))
if (a.radius==b.radius)
test=all(a.xyz==b.xyz);
else
test=false;
end
else
test=false;
end
end

 Akzeptierte Antwort

Matt J
Matt J am 13 Jun. 2013
Bearbeitet: Matt J am 13 Jun. 2013

0 Stimmen

Perhaps as follows
function test=eq(a,b)
test = all([a.xyz]==[b.xyz]) & all([a.radius]==[b.radius]);
end

3 Kommentare

Daniel Shub
Daniel Shub am 13 Jun. 2013
Bearbeitet: Daniel Shub am 13 Jun. 2013
The ISEQUAL function might be better since it handles unequal size and unequal class vectors.
Daniel
Daniel am 13 Jun. 2013
A couple of problems with this, since xyz is a 1x3 array, if the object is empty, xyz is just [] and this will through a "matrix dimensions must agree" error, which is why I had the size comparison to start with.
Also, because xyz is a [1x3] double, and I want all of x y and z to be equal, it's necessary to use all( ) on the xyz portion. This works on single objects, but when I do a comparison of arrays, for example a 1x2, if both elements are the same I get [1, 1] as expected, but if one is the same and one is different, I get [0, 0].
Matt J
Matt J am 13 Jun. 2013
Bearbeitet: Matt J am 13 Jun. 2013
if both elements are the same I get [1, 1] as expected
That expectation was not evident. For all we can tell, you are looking for behavior similar to ISEQUAL, which always returns a scalar true/false output, regardless of the inputs' sizes. You also shouldn't be getting a non-scalar output from my code.
But if you do want non-scalar true/false output, you would instead do this
function test=eq(a,b)
if ~isequal(size(a), size(b))
error 'Dimension Mismatch'
end
xyz_eq=all(vertcat(a.xyz) == vertcat(b.xyz),2);
%assumes xyz are row vectors
radius_eq=vertcat(a.radius)==vertcat(b.radius);
test = reshape(xyz_eq & radius_eq, size(a));
end
if the object is empty, xyz is just [] and this will through a "matrix dimensions must agree" error, which is why I had the size comparison to start with.
The "dimensions must agree" error is consistent with the normal behavior of EQ for numerical arrays, e.g.,
>> [1,2,3]==[]
Error using ==
Matrix dimensions must agree.
It's not clear why you would want to be getting rid of it now.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Data Type Identification finden Sie in Hilfe-Center und File Exchange

Produkte

Gefragt:

am 13 Jun. 2013

Community Treasure Hunt

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

Start Hunting!

Translated by