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
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.
采纳的回答
darova
2020-2-18
5 个评论
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
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 Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!