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

2 次查看(过去 30 天)
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 个评论
Rik
Rik 2020-2-18
@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
Thanks matlab experts, that was the problem. Will use numel.

请先登录,再进行评论。

采纳的回答

darova
darova 2020-2-18
  5 个评论
Rik
Rik 2020-2-19
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 2020-2-19
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by