fsolve with variable undeclared - converting to web app

5 views (last 30 days)
I am attempting to convert a function that used to solve with vpasolve into a function that will solve on the matlab web app.
The original equation to solve was the following:
app.Q_Intrinsic=pi*app.ng*app.Ring_Length*sqrt(a)/app.lambda0/(1-a)
This works fine on a desktop compiled version of the app due to symbolic toolbox meaning I can define the variable a as syms a, before I run vpa solve. However, without syms toolbox, I am unsure how to format the following lossCalc function to allow me to pass in the LossFunction into fsolve.
function lossCalc(app)
a = fsolve(@(a) lossFunc,1);%field loss
alpha = -2*log(a)/app.Ring_Length;
app.Alpha = alpha/100*4.34; %cm
end
function fval = lossFunc(app,a)
app.Q_Intrinsic=pi*app.ng*app.Ring_Length*sqrt(a)/app.lambda0/(1-a);
end

Answers (1)

Varun
Varun on 8 Sep 2023
Hi George,
Looks like you want to solve the “Loss Function” equation using “fsolve”. You have shared a code snippet for the same which seems to be incomplete and some syntactical errors.
Please find the updated code which is complete and flawless:
function lossCalc(app)
% correct way to pass anonymous function which calls lossFunc.
a = fsolve(@(x) lossFunc(x,app), 0.5);
alpha = -2*log(a)/app.Ring_Length;[AK1]
app.Alpha = alpha/100*4.34; % cm
end
function fval = lossFunc(x, app)
app.Q_Intrinsic = pi*app.ng*app.Ring_Length*sqrt(x)/app.lambda0/(1-x);
% lossFunc should also return the value of app.Q_Intrinsic
fval = app.Q_Intrinsic;
end
In this modified version:
  1. The anonymous function “@(x) lossFunc(x,app)” is passed as the first argument to “fsolve”. This anonymous function takes ‘x’ as the input and calls the “lossFunc” function passing input arguments ‘x’ and “app”(additional argument).
  2. The “lossFunc” function takes two input arguments, ‘x’ and “app”. It calculates the intrinsic Q factor (app.Q_Intrinsic) based on the given parameters of app and input argument ‘x’.
  3. The calculated app.Q_Intrinsic value is returned as the output of lossFunc.
You can also adjust the initial guess value (0.5 in this case) passed to “fsolve” as needed. This value should be close to the expected solution for faster convergence.
Please refer the following page to learn more on using “fsolve”:
Hope this helps.

Community Treasure Hunt

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

Start Hunting!