Azzera filtri
Azzera filtri

function with duplicate name cannot be defined

5 visualizzazioni (ultimi 30 giorni)
i wrote the following function and saved it as myobjective.m
Function i used
function obj= myobjective(p)
global c1meas c2meas c3meas c4meas c5meas
%simulate model
c=simulate(p);
obj = sum(((c(:,1)-c1meas)).^2)
+ sum(((c(:,2)-c2meas)).^2)+sum(((c(:,2)-c3meas)).^2)+sum(((c(:,2)-c4meas)).^2)+sum(((c(:,2)-c5meas)).^2);
end
while running the function i am getting the following error ...
Error: File: myobjective.m Line: 2 Column: 15
Function with duplicate name "myobjective" cannot be defined.
i used all _my objective in command window and i got only 1 m file with that name...
pls help me guys.....
  4 Commenti
Anne Davenport
Anne Davenport il 1 Nov 2023
I had the same error and it came from a very sneaky source.
My function has a large header of comments. Each comment line starts with a ' % '.
One of those ' % ' got turned into a ' ! '. That's all it took to get the "Function with duplicate name cannot be defined." error message. I can turn the error on and off with just one little ' ! '.
I hope MATLAB can get a better error message for a stray ' ! '.
Steven Lord
Steven Lord il 1 Nov 2023
That "little" exclamation mark turns the line it starts into a command to send to the operating system. If that's the first line in the file, and the second line now starts with the keyword function, that makes the file a script with a local function inside. As stated in the section describing requirements for functions names on this documentation page "Script files cannot have the same name as a function in the file." I suspect the file and the function have the same name since without the ! the file was a function file and the best practice is to have the first (main) function in the file have the same name as the file.
Sometimes "little" characters can have a big impact! After all, there's a big difference if the balance in your bank account is $1,000 or -$1,000.

Accedi per commentare.

Risposte (1)

Steven Lord
Steven Lord il 25 Ago 2019
The error message states that the function definition is on the second line of the file, so I suspect you have other code on the first line. That makes that file a script file with a function in it, and according to the documentation "Script files cannot have the same name as a function in the file."
Rename either your script file or your function, or if you intended this file to be a function file rather than a script file remove the executable code on the first line of the file.
  1 Commento
vinutha paravastu
vinutha paravastu il 25 Ago 2019
thanku it solved my problem...
in the first line i wrote a comment with out % symbol might be it was taken as code...

Accedi per commentare.

Categorie

Scopri di più su Manage Products in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by