MyFunction Call generates Error
显示 更早的评论
I am facing some problems in executing my code main.m which calls a function called Myfunction.m,I hope someone can help me to resolve that problem :
clc;
clear all;
close all ;
dim1=5;
dim2=3;
Freq=3e9;
Gr=20; % Receive Antenna Gain
Gt=2; % Transmit Antenna Gain
P_T=0.001; %watt (Transmit Power)
PathLossExponent=2;
std=2;
ReaderLoc = [dim1/3 dim2/3; dim1/3 2*dim2/3;
2*dim1/3 dim2/3; 2*dim1/3 2*dim2/3];
mobileLoc = dim1*rand(1,2);
for m = 1:3
distanceB(m) = sqrt( (mobileLoc(:,1)-ReaderLoc(m,1)).^2 + (mobileLoc(:,2)-ReaderLoc(m,2)).^2 );
[PrMob,Pr0,Dref] = Myfunction(P_T, Gt, Gr, Freq, PathLossExponent,distanceB(m),std);
PrMobNode(m) = PrMob;
end
%the above main code should get a return value calculated by Myfunction.m%%
%%%%%Myfunction.m%%%%% looks like :
C=physconst('Lightspeed')
function [Pr,Pr0,Dref] = Myfunction(PTx , TXAntennaGain, RXAntennaGain, Freq, PathLossExponent,DistanceMsr,std)
Dref=0.5;
PTxd = 10*(log10(PTx));
Wavelength = C/Freq;
M = Wavelength/(4*pi*Dref);
Pr0= PTxd +2*TXAntennaGain +2*RXAntennaGain - 40*log10(1/M);
GaussRandom=normrnd(0,std);
Pr= Pr0 - (20*PathLossExponent* log10(DistanceMsr/Dref)) + GaussRandom;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The errors generated are:
1) when executing the function code:
Error: File: Myfunction.m Line: 3 Column: 26
Function with duplicate name "Myfunction" cannot be defined.
2)when executing the main.m
Error: File: Myfunction.m Line: 3 Column: 26
Function with duplicate name "Myfunction" cannot be defined.
Error in main (line 24)
[PrMob,Pr0,Dref] = Myfunction(P_T, Gt, Gr, Freq, PathLossExponent,distanceB(m),std);

回答(2 个)
The problem is that you think that you wrote a function, but you actually wrote a script:
These are the first three lines of your script:
C=physconst('Lightspeed') % <------ this line makes it a script!
function [Pr,Pr0,Dref] = Myfunction(...)
A function must not have any code outside of any function definitions. Your C=... line is how you told MATLAB that you want a script, not a function, because it is not inside a function definition. That means that your script (known to MATLAB by its filename) includes a local function which has the same name as the script itself: Ouch! That is why it throws an error.
The solution is simple: get rid of all code that are not inside the main or local function definitions.
1 个评论
Adam Danz
2019-4-30
@ ilyass ilyass, check out the link below for an example of a function and an example of a script that contains a function. Only comments can come before a function declaration unless you're writing a script.
类别
在 帮助中心 和 File Exchange 中查找有关 Array Geometries and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!