필터 지우기
필터 지우기

How do you overload a built-in function if it has no parameters?

조회 수: 5 (최근 30일)
Joel
Joel 2011년 10월 27일
In order to debug some code, I'm trying to overload the rand and randn functions. I re-arranged some code to better take advantage of vector operations but the liberal use of the rand and randn functions are making it difficult to compare results against the original code. Long story short, I want to create versions of the rand and randn functions that output constant values.
I've had no problem overloading the functions when I specificy output dimensions (e.g. rand(3,1)) but I am at a loss as to how to override the no parameter version which outputs a single scaler. No parameter means no data type to associate the overloaded function with.

답변 (2개)

Jan
Jan 2011년 10월 27일
The rand.m file must only appear early in the Matlab path.
function R = rand(varargin)
switch nargin
case 0
R = 3;
case 1
R = repmat(3, varargin{1}, varargin{1});
otherwise
R = repmat(3, [varargin{:}]);
end
  댓글 수: 1
Joel
Joel 2011년 10월 27일
Thanks for the response Jan. I may be misunderstanding your answer but I believe that only works for user functions, not built in matlab functions. Matlab will look for a built in function before searching the mstlab path.
http://www.mathworks.com/help/techdoc/matlab_prog/f7-58170.html#bresuvu-6
There is a method for dealing with this but its baed on the data type of the parameters passed to the function. Unfortunately with the rand function, it doesnt always need parameters and therefore it isnt obvious how to override it.

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


Daniel Shub
Daniel Shub 2011년 10월 27일
Another option would be to reset the random number generator prior to running the original version and then again before running the new version.
  댓글 수: 1
Joel
Joel 2011년 10월 27일
This actually doesnt work because operations happen in a different order and are grouped differently in the newer code. I would need to resetthe state before every single call which really isnt practicle for my application.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by