guodi
guodi

Reputation: 37

create function with the same name as a builtin function in MATLAB

gpuArray is a function used to create array on GPU in matlab. Here I don't always want to use the gpuArray, so I write a function called gpuArray (below) to return a normal matrix when necessary, so I don't need to change the code much. I have already added this function to the path. But when I call the gpuArray function, it still return a gpuArray.....does anyone know why....thanks a lot!

function A = gpuArray(A)

Upvotes: 0

Views: 720

Answers (2)

Staus
Staus

Reputation: 651

This is....not the best idea. Having multiple functions with the same name will end up leading to quite a bit of ambiguity that a search + replace on your code to an alternate function with a unique name won't cause. But if you insist on doing this, then you need to be conscious of how MATLAB searches for functions. The order is (from http://au.mathworks.com/help/matlab/matlab_prog/function-precedence-order.html):

  1. Imported package functions

  2. Nested functions within the current function

  3. Local functions within the current file

  4. Private functions

  5. Object functions

  6. Class constructors in @ folders

  7. Functions in the current folder

  8. Functions elsewhere on the path, in order of appearance

So to make sure your function takes precedence over the built-in function it needs to be higher on that list. You can include your function as a sub-function in the current file (#2 or #3), a private function (#4), create a class and use those functions (#5 and 6), put your function in the same folder as the code invoking it (#7) or ensure that your function is in a folder higher up in the search path than the built-in function (#8). I suspect that your \Documents\MATLAB folder or whichever your gpuArray function is in is actually lower in your folder path than the built-in function so #8 above fails. You can move the place of that folder in your search path or, a better idea, change the name of your function to something unique and change the code that calls it.

Upvotes: 2

chipaudette
chipaudette

Reputation: 1675

You should always be able to type "which gpuArray" to find out which "gpuArray" that Matlab will invoke. I'm assuming that it will not point to yours.

To try to get Matlab to use your gpuArray, you should try adding the path to your function to the Matlab path. Try something like:

%add the path to *my* gpuArray function
addpath('C:\MyDirectory\SomeOtherDirectory\MyMfiles\');

Good luck!

Upvotes: 1

Related Questions