How to Call a function inside for loop?

조회 수: 17(최근 30일)
Vaswati Biswas
Vaswati Biswas 2021년 11월 19일
편집: Stephen23 2021년 11월 19일
I am writing a function like this
function Eqn = eff(neff,hf)
nf=vpa(2.1511);
ns=vpa(1.5264);
nc=vpa(1.3354);
rho=1;
lambda=532.3;
Eqn = (((2*pi./lambda)*(sqrt(nf^2-neff.^2)*hf))-atan((nf/nc)^(2*rho)*sqrt ((neff.^2-nc^2)/(nf^2-neff.^2)))-atan((nf/ns)^(2*rho)*sqrt ((neff^2-ns^2)/(nf^2-neff.^2))) -(m*pi))==0;% equation 8 from paper
end
then I am calling it inside a for loop using the following code
hf = 75:20:350;
m= 0;
NEFF = zeros(size(hf));
for ii=1:numel(hf)
options = optimoptions('fsolve','Display','none','PlotFcn',@optimplotfirstorderopt);
neff = [0,5];
NEFF(ii)=fsolve(@(neff,hf(ii))eff(neff),neff,options
end
plot(hf, NEFF)
But I am getting an error
Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for
mismatched delimiters.
what mistake I am making here? Kindly help
  댓글 수: 1
Stephen23
Stephen23 2021년 11월 19일
편집: Stephen23 2021년 11월 19일
Your code is missing severay parentheses and that anonymous function is not defined correctly.
Replace this
NEFF(ii)=fsolve(@(neff,hf(ii))eff(neff),neff,options
with something like
fnh = @(n)eff(n,hf(ii));
NEFF(ii) = fsolve(fnh,neff,options);
But I cannot run your code as the objective function needs to be debugged first.

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

채택된 답변

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 11월 19일
Here is the corrected code, but still you should check the equation. The found roots are complex valued:
hf = 75:20:350;
NEFF = zeros(size(hf));
for ii=1:numel(hf)
options = optimoptions('fsolve','Display','none','PlotFcn',@optimplotfirstorderopt);
neff = [0; 5];
NEFF(ii)=fsolve(@(hf) eff(hf(ii), neff), neff,options);
end
%plot(hf, NEFF)
function F = eff(hf, neff)
nf=(2.1511);
ns=(1.5264);
nc=(1.3354);
rho=(1);
lambda=(532.3);
m=(0);
F = (((2*pi./lambda)*(sqrt(nf^2-neff.^2)*hf))-atan((nf/nc)^(2*rho)*sqrt ((neff.^2-nc^2)/(nf^2-neff.^2)))-atan((nf/ns)^(2*rho)*sqrt ((neff.^2-ns^2)/(nf^2-neff.^2))) -(m*pi));% equation 8 from paper
end
  댓글 수: 1
Stephen23
Stephen23 2021년 11월 19일
편집: Stephen23 2021년 11월 19일
"Here is the corrected code.."
Note that this code completely ignores the values of hf defined on the first line. I doubt that is the intent.

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

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by