필터 지우기
필터 지우기

function with duplicate name cannot be defined

조회 수: 5 (최근 30일)
vinutha paravastu
vinutha paravastu 2019년 8월 25일
편집: Walter Roberson 2023년 11월 1일
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
Anne Davenport
Anne Davenport 2023년 11월 1일
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 2023년 11월 1일
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.

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

답변 (1개)

Steven Lord
Steven Lord 2019년 8월 25일
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
vinutha paravastu
vinutha paravastu 2019년 8월 25일
thanku it solved my problem...
in the first line i wrote a comment with out % symbol might be it was taken as code...

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by