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

 採用された回答

Matt J
Matt J 2013 年 6 月 13 日
編集済み: Matt J 2013 年 6 月 13 日

0 投票

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

3 件のコメント

Daniel Shub
Daniel Shub 2013 年 6 月 13 日
編集済み: Daniel Shub 2013 年 6 月 13 日
The ISEQUAL function might be better since it handles unequal size and unequal class vectors.
Daniel
Daniel 2013 年 6 月 13 日
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 2013 年 6 月 13 日
編集済み: Matt J 2013 年 6 月 13 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeData Type Identification についてさらに検索

製品

質問済み:

2013 年 6 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by