How to Fix “function with duplicate name cannot be defined” Error in MATLAB

Share it to your friends

MATLAB is a widely used language in the mathematics and science field, mostly due to its flexibility and wide array of functions.

With MATLAB, you can create various scientific models, create a visualization from various data sources, and a lot more. The syntax of MATLAB is also arguably easy to learn, leading to its widespread adoption.

MATLAB scripts are stored in .m file. It can be executed in the main MATLAB interface. However, as with every programming language, MATLAB scripts can produce errors too when syntax or file handling errors occur.

One of the most common errors in MATLAB is “function with duplicate name cannot be defined”, which will prevent the entire script to execute. Fortunately, it can be resolved pretty easily by following these steps.

The first step you need to do is to check your script for errors. You might have accidentally declared a function with the same name in the same script. Rename the offending function name and then try rerunning the script.

Usually, you can see the offending function name in the error message. If you have renamed the function and the script still does not work, follow the next step.

If you have tried renaming the function to no avail, the next step you should try is to rename the MATLAB script file. The .m file name should not be the same as the script file. For example, if the MATLAB function name is MyFunction.m, rename your script as itsmyfunction.m, and call it appropriately in your code.

To call the script in MATLAB, you can use this following script in the .m file after renaming it:

function [res] = DoStuff(param) % Note that there is no executable line before this
res = myFunction(param)

And use the code here to call the function in the .m file:

addpath('./SubFolder/SubSubFolder'); %SubSubFolder contains mex file defining myFunction
close all;
res = DoStuff(param); %Calling the function
function [res] = DoStuff(param)
res = myFunction(param)

The code was helpfully provided by Sardar Usama in Stack Exchange.
If all else fails, try running your MATLAB script on another computer.

Sometimes MATLAB fails to detect the saved file in your computer, and running the script on another computer might help you get past the “function with duplicate name cannot be defined” error.

If your script runs fine on another computer, you might want to reinstall MATLAB on your computer.

Leave a Comment