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

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

darova
darova 2020년 2월 18일
Did you try
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.
Thanks matlab experts, that was the problem. Will use numel.

댓글을 달려면 로그인하십시오.

 채택된 답변

darova
darova 2020년 2월 18일

0 개 추천

댓글 수: 5

Remember about preallocation for faster execution
r = 0*a;
% r = zeros(size(a));
Neither of those works here, r = 0*a calls into my overloaded mtimes operator and doesn't create an array of 0's, and if I write r = zeros(numel(a)) then inside my for loop I get a "Conversion to double is not possible" error since I'm ultimately filling the array with instances of my class, not with doubles.
darova
darova 2020년 2월 19일
Hm, im not that good in MATLAB
Maybe someone of experts can suggests something
But one thing i suggest is defintely preallocation
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).
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개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

릴리스

R2019b

태그

질문:

2020년 2월 18일

댓글:

2020년 2월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by