Solve nonlinear equation- problem with fzero results

Hello everybody,
I am quite new for the Matlab world and currently struggling with most probably easy problem, but as I can not fix it I need also your expertise :)
I created a for loop and try to solve nonlinear equation by using the fzero function.
Unfortunately the returned results are not exactly what I expected.
Can someone look into the code and give me feedback if I have any general mistakes? Do I call the variables in a correct way in the function? Unfortunately if I just add them in "function F = Eq_Sys1(Y, C, xe, i...)" it returns error message and it was only possible by using evalin. Is there any better way to call the parameters in the function? Is the for loop working correct together with this external function (i mean is the function executed after each iteration)?
Thank you for your feedback and proposals :)
...
...% all used variables loaded
for i= 1:20
x(1)= 20;
x(i+1)=x(i)+250;
SPi(i) = (x(i)*xe/sqrt(3));
Z(i) = c2+(kmv*(T-T0)+c1)*x(i);
fun = @Eq_Sys1;
Y0 = 0;
Y(i) = fzero(fun,Y0);
%Function Body
function F = Eq_Sys1(Y)
k1_x = evalin('base','k1_x'); %call variable in the function
xe = evalin('base','xe');
R = evalin('base','R');
k2 = evalin('base','k2');
i=evalin('base','i');
x(i) = evalin('base','x(i)');
SPi(i) = evalin('base','SPi(i)');
C = evalin('base','C');
Z(i) = evalin('base','Z(i)');
F = Y-1/k2*log(-(((-30/pi/x(i)*C+90/pi/x(i)*Y*(1/sqrt(3)*xe*x(i)+R*Y))+Z(i))...
/k1_x+1)/((-30/pi/x(i)*C+90/pi/x(i)*Y*(1/sqrt(3)*xe*x(i)+R*Y)+Z(i))/k1_x-1));
end

Answers (1)

You don't seem to have an "end" to go with your "for" loop.
x(1) = 0 can go before the "for" loop.
Insted of
...
fun = @Eq_Sys1;
Y0 = 0;
Y(i) = fzero(fun,Y0);
you could have:
...
Y0 = 0;
Y(i) = fzero(@Eq_Sys1,Y0,[], k1_x, xe, ...etc);
% in which case your function would need to accept the extra inputs
F = Eq_Sys1(Y, k1_x, xe, ...etc)
% and you could then eliminate the need for the evalin's within the function
However, this might or might not produce what you expect. We could test it if you were to upload your complete code and data.

Categories

Find more on Optimization in Help Center and File Exchange

Products

Asked:

on 26 Aug 2020

Answered:

on 26 Aug 2020

Community Treasure Hunt

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

Start Hunting!