MATLAB Answers

How do you use ./ operator on array of custom class

3 views (last 30 days)
Hi,
I've written a custom class with overloads for mathematical operators. I now have arrays a and b and I want to do element-wise division.
My first guess was that the ./ operator would map the / operator over the elements of the array, however with mrdivide defined I get the error "Undefined operator './' for input arguments of type".
When I add the following code to my class
function r = rdivide(a, b)
for i = 1:length(a)
r(i) = a / b
end
end
I get the error "Error using / Too many input arguments" with line numbers pointing into my mrdivide function. My mrdivide function seems to work when I use it on its own.
Is this the correct way to implement element-wise division?
Thanks.

  3 Comments

Rik
Rik on 18 Feb 2020
@Darova that looks like an answer to me. When moving it to the answer section, could you make it code instead of an image?
I also have a suggestion for the code itself: use numel instead of length. That way this overload will also work for non-vector shaped arrays.
Jefferson Carpenter
Jefferson Carpenter on 18 Feb 2020
Thanks matlab experts, that was the problem. Will use numel.

Sign in to comment.

Accepted Answer

darova
darova on 18 Feb 2020

  5 Comments

Show 2 older comments
darova
darova on 19 Feb 2020
Hm, im not that good in MATLAB
Maybe someone of experts can suggests something
But one thing i suggest is defintely preallocation
Rik
Rik on 19 Feb 2020
Preallocation is a lot less important when dealing with an array of objects than it is with arrays of native Matlab data types. In this case r=a; could be enough (since you will be overwriting the entries anyway).
Steven Lord
Steven Lord on 19 Feb 2020
If you want functions like zeros, ones, etc. to be able to create arrays of your objects filled with the equivalent of 0 or 1 in your class, see this documentation page.

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Tags

Products


Release

R2019b