1

I was wondering if it is possible to replace this:

function y = par(Z1,Z2)
y=1./(1./Z1+1./Z2);
return;

with some sort of "operator overloading" as in the language C++. So lets say it would become possible to call the function "Z1#Z2" instead of "par(Z1,Z2)"

5
  • Yes, but Z1 and Z2 would need to be of a custom class, obviously (as in good-practice C++). Start reading about MATLAB's OOP capabilities here. The question you should ask yourself is: is replacing this one function by some nicer syntax really worth the trouble of writing the class? Commented Apr 16, 2014 at 7:25
  • 1
    I would also re-write that as Z1.*Z2./(Z1+Z2) Commented Apr 16, 2014 at 7:28
  • Even using a custom class would not work because # would need to be a valid and overloadable operator in matlab, which it is not. The same is true for C++ though I'm not entirely sure of that. Commented Apr 16, 2014 at 7:29
  • @Tobold: Nope, # is not a C++ operator, let alone an overloadable one :) Commented Apr 16, 2014 at 7:31
  • @RodyOldenhuis: That C++ doesn't allow it is cristal clear to me. Though it would be nice to know definetly wheter the rule applies also to matlab Commented Apr 16, 2014 at 8:08

2 Answers 2

4

Here's an example:

classdef myClass < double

    methods

        %// constructor
        function this = myClass(varargin)
            this = this@double(varargin{:});
        end

        %// Special syntax for harmonic mean
        function new = mldivide(this, other)
            new = this.*other./(this + other);
        end

    end

end

Usage:

>> Z1 = myClass(rand(4));
>> Z2 = myClass(rand(4));
>> Z3 = Z1 \ Z2;              %// calls your harmonic mean function
Sign up to request clarification or add additional context in comments.

Comments

1

MATLAB does support operator overloading, but not in the way that you're envisioning. Operator overloading can only be performed on your own custom classes that you create in MATLAB.

Check out http://www.mathworks.com/help/matlab/matlab_oop/implementing-operators-for-your-class.html. If you seriously want to do operator overloading, you will need to learn about MATLAB's Object Oriented Programming paradigm first.

Check this link out: http://www.mathworks.com/help/matlab/object-oriented-programming.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.