MATLAB - overload assignment operator

Tag: oop , matlab Author: jiayaozhang0114 Date: 2011-11-05

Suppose I have the following class:

classdef myClass < handle
        A = [10 20 30 40]

Then suppose I have the following calls:

>> m = myClass;
>> n = m;

n will be a handle to the same object as m is, of course. Is there a way to overload the assignment operator? In particular, I wonder if I can have something like the following method:

function val = assign(obj)
    val = obj.A;

So doing n = m would act the same as n = m.A.

Best Answer

I don't think you can: just imagine how you would assign the object itself to a variable, it would be the exact same syntax. And since you can't have ambiguities for a program to be executable, it is very unlikely to be possible and useful.

If you'd just want it as syntactic sugar, learn to live with the limitations. Otherwise you might want to take another look at your design.

Other Answer1

It's not possible to overload the = operator to do this.

But (as you probably realised) there's no reason why you can't implement your assign method as you have done, and then call n = assign(m).