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.

 채택된 답변

John D'Errico
John D'Errico 2014년 12월 19일

1 개 추천

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

Zoltán Csáti
Zoltán Csáti 2014년 12월 19일
Well, both answers were totally useful for me. Is there a chance to accept both of them? I just cannot decide between them.
Just flip a coin. :) Better yet, use MATLAB!
accept = {'Sean', 'John'};
accept{1 + round(rand(1))}
Drat. I tried it a few times, but it can't make up its mind!
Sean de Wolski
Sean de Wolski 2014년 12월 19일
You can give them both a vote at least!
Zoltán Csáti
Zoltán Csáti 2014년 12월 19일
Well, John won it using the advice above. :)
Dang!
You should've used:
accept{1+floor(rand)}
Or set the random number generator to the year, that would at least be fair...
rng(2014)
1+round(rand)

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

추가 답변 (2개)

Matt J
Matt J 2014년 12월 19일

2 개 추천

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
Sean de Wolski 2014년 12월 19일
Ughh that hurts...
Matt J
Matt J 2014년 12월 20일
Yeah, just an illustration of some of the horrible things you can do.

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

Sean de Wolski
Sean de Wolski 2014년 12월 19일
편집: Sean de Wolski 2014년 12월 19일

1 개 추천

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

카테고리

도움말 센터File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품

태그

질문:

2014년 12월 19일

댓글:

2014년 12월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by