Overload mtimes for double*char

조회 수: 3 (최근 30일)
Jeppe
Jeppe 2013년 1월 30일
I am working on a Matlab class that handles numbers/matrices with physical units. I would like the user to be able to write the input as (double)*(char), like this:
L = 10*m % L is ten meters long
This operation calls the mtimes function for the double class. I can easily overload this function and make it work as I want with respect to (double, char)-input, but I still want it to work normally for (double, double)-input. Using * inside the mtimes function with (double, double)-input simply refers the function back to itself, resulting in an infinite regression.
Can I modify the original double mtimes function, or how do I go about this?
Thanks

채택된 답변

James Tursa
James Tursa 2013년 1월 30일
편집: James Tursa 2013년 1월 30일
The short answer is DON'T DO THIS! There are many built-in MATLAB functions that do (double)*(char) operations and depend on getting double results. If you overload this operation with your own you will end up breaking a bunch of built-in MATLAB functions. (And also potentially breaking any other code you happen to download from others, such as from the FEX).
To answer your question directly, however, you can sometimes use the function named 'builtin' to do things like this (but DON'T DO IT for your proposed case!)
  댓글 수: 1
Jeppe
Jeppe 2013년 1월 30일
I accept your point. Breaking downloaded stuff is not a big concern of mine, but I do not want to mess up my internal Matlab. Here is my implementation, where calls to mtimes from some internal Matlab file is handled as usual, while calls from other files (not placed in the Matlab root) is handled as I want them to be. I hope you find this solution acceptable.
function C = mtimes(A, B)
% If mtimes is called internaly from Matlab,
% the built-in function should be used:
ST = dbstack('-completenames');
callers = {ST.file};
if length(callers) > 1
last_caller = callers{end-1};
root = matlabroot;
if strcmp(last_caller(1:length(root)), root)
C = builtin('mtimes', A, B);
return
end
end
% The call is from a user:
if isa(A, 'double') && isa(B, 'char')
C = unit(A, B);
else
C = builtin('mtimes', A, B);
end
end

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

추가 답변 (2개)

Matt J
Matt J 2013년 1월 30일
You should define your own char class (e.g., mychar) with its own mtimes method.

Jeppe
Jeppe 2013년 1월 30일
Thanks for the responses. The builtin function works perfectly.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by