Overload basic arithmetic for classes arrays?

2 views (last 30 days)
Alex Kashuba
Alex Kashuba on 24 Mar 2020
Answered: Deepak on 14 Nov 2024
I have a an object obj with several fields, say
obj.a = [1 -1];
obj.b = [0 1; 0 0];
and can override a plus operator
obj = obj1 + obj2
as
obj.a = obj1.a + obj2.a
obj.b = obj1.b + obj2.b
The QUESTION 1: What if I have a class arrays, say obj1(1,2) and obj1(2,1) and want to sum them in the same way as it is performed for double i.e. getting obj(2,2)? Of course I need it for the arbitrary sizes and dimensions. Function arrayfun() is no help, since it does not do implicit expansion. The bsxfun() would do the job, but it is defined for double, int, char, etc.
The QUESTION 2: Same question for mtimes: how can i do matrix multiplication if times function is defined?

Answers (1)

Deepak
Deepak on 14 Nov 2024
The task of overloading the plus operator for a custom MATLAB class can be achieved by defining a method named plus within the class that dictates how two instances of the class should be added.
First, determine the sizes of the input object arrays and compute the resulting size using max(size(obj1), size(obj2))” function. Next, expand the input arrays to this common size using repmat” function, ensuring that each element aligns correctly for addition. Finally, iterate over the expanded arrays, performing the addition operation on each corresponding element's properties, and return a new array of the custom objects containing the summed results.
Here is the MATLAB code to achieve the same:
classdef MyObject
properties
a
b
end
methods
function obj = MyObject(a, b)
if nargin > 0
obj.a = a;
obj.b = b;
end
end
function obj = plus(obj1, obj2)
size1 = size(obj1);
size2 = size(obj2);
% Determine the resulting size using implicit expansion rules
resultSize = max(size1, size2);
% Expand obj1 and obj2 to the resulting size
obj1 = repmat(obj1, resultSize ./ size1);
obj2 = repmat(obj2, resultSize ./ size2);
% Perform element-wise addition
obj(resultSize(1), resultSize(2)) = MyObject();
for i = 1:resultSize(1)
for j = 1:resultSize(2)
obj(i, j).a = obj1(i, j).a + obj2(i, j).a;
obj(i, j).b = obj1(i, j).b + obj2(i, j).b;
end
end
end
end
end
%Test Script
obj1(1, 1) = MyObject([1 -1], [0 1; 0 0]);
obj1(1, 2) = MyObject([2 2], [1 0; 0 1]);
obj2(1, 1) = MyObject([3 3], [1 1; 1 1]);
obj2(2, 1) = MyObject([0 -1], [0 0; 1 0]);
% Perform addition with implicit expansion
sumObj = obj1 + obj2;
For more information on the functions used refer to the following documentation:
I hope this assists in resolving the issue.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!