Define a new binary operator in MATLAB?

Hi,
I wondered whether it is possible to define a new, binary operator in MATLAB. The thing is, I need a new operator to "multiply" two matrices in an uncommon way, like this:
A = [.5 .5 0; 0 1 0; 0 .5 .5];
B = [.5 .5 0; 0 1 0; 0 .5 .5];
RowsA = size(A,1);
ColsA = size(A,2);
RowsB = size(B,1);
ColsB = size(B,2);
C = zeros(RowsA*RowsB, ColsA*ColsB);
for i = 1:RowsA
for j = 1:ColsA
C( 1+(i-1)*RowsB:i*RowsB, 1+(j-1)*ColsB:j*ColsB ) = A(i,j) * B;
end
end
Instead of making a function and calling C = myfunction(A,B), I'd like to use C = A # B, with # the new operator (or perhaps another symbol if this is not possible).

 采纳的回答

Jan
Jan 2012-4-24
You cannot define a new operator in Matlab using non-standard symbols like #.
While using myFunction(A, B) is a perfect solution already, you can create a new object type for the matrices and overload the standard operators. E.g. for A+B the code plus(A, B) is called implicitly. But the restriction to standard operator characters +-*/\ and [] will reduce the readability. Therefore I prefer myFunction().

2 个评论

Thanks @Jan for your answer. Would it perhaps be possible to add some functionality to the ^ operator for matrices? So instead of the A^2 and A.^2 for example, define A^B where A and B are both matrices?
That would be the method named "mpower", and you would have the same restrictions as Jan noted -- i.e., you would have to use a different object type rather than simple number matrices.

请先登录,再进行评论。

更多回答(0 个)

类别

标签

Community Treasure Hunt

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

Start Hunting!

Translated by