Can we define operators in MATLAB?
2 次查看(过去 30 天)
显示 更早的评论
I started learning OOP in MATLAB and I saw that we can either use the colon(A,B) syntax or simply A:B. This kind of method works for other operators and we may even redefine how they work.
My question is: can we somehow achieve that MATLAB recognises some other symbols we define? For example, I want to use ° for dyadic product in my class and if I typed A°B, dyadic(A,B) would be executed on objects A and B.
0 个评论
采纳的回答
John D'Errico
2014-12-19
As you have seen, you can define the behavior of existing operators, like + or * to operate as you would like them to behave for objects of your class. I use that capability heavily in several of my toolboxes.
But no, you cannot define a completely new character and have MATLAB recognize that as an operator. So you cannot define the operator $ or ° to do something special for your class. This may change one day - one can never rule out language design changes.
6 个评论
Sean de Wolski
2014-12-19
Or set the random number generator to the year, that would at least be fair...
rng(2014)
1+round(rand)
更多回答(2 个)
Matt J
2014-12-19
There are fake things you can do. I don't really recommend them, but just for fun, I create a function below that makes the '$' symbol act like the '+' symbol,
>> A=1;B=2;
>> Q C=A$B
>> ans=C
ans =
3
function Q(varargin)
cmd=[varargin{:} ';'];
cmd=strrep(cmd,'$','+');
evalin('caller',cmd)
2 个评论
Sean de Wolski
2014-12-19
编辑:Sean de Wolski
2014-12-19
No, you can only overload the current operators. I think this is pretty close to the full list
le,lt,gt,ge,eq,ne,colon,end,times,mtimes,ldivide
rdivide,mrdivide,mldivide,power,mpower,subsref,subsindex,subsasgn
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Software Development Tools 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!