Jac might be unused, but I am using the Jac value.

1 visualizzazione (ultimi 30 giorni)
function Test2
clear
n=2;
Jac=zeros(n); fv=zeros(n,1); f=zero(n,1); Cd=zeros(n,1); C=zeros(n,1);
C=[0.3;0.5];
Ca0=1;V=100; Q=50; k1=1; k2=1; al=0.5;
Rel_dx=0.01;
itr_max=100; tol=10^-4;
for k=1:itr_max
Jac=J(C);
fv=fx(C);
f=-1.*fv';
d=Jac\f;
C=C+d;
Rerr=d./C;
max_err=max(abs(Rerr));
fprintf('CA1=%f CB=%f, CC=%f, CD=%f max_err=%f\n', C, max_err)
if max_err<tol; break; end
end
if k==itr_max
fprintf('Newtons Method Failed to converge in %d iterations\n', itr_max)
end
if i<itr_max
fprintf('The solution is CA1=%f and CA2=%f in %d iterations\n',C,k)
end
function Jac=J(C)
fv=fx(C);
for j=1:n
C(j)=C(j)*(1+Rel_dx);
for i=1:n
Jac(i,j)=(fvd(i)-fv(i))/C(j)/Rel_dx;
end
C(j)=C(j)/(1+Rel_dx);
end
end
function fv=fx(C)
fv(1)=Q*Ca0-Q*C(1)-k1*C(1)^2*(al*V);
fv(2)=Q*C(1)-Q*C(2)-k2*C(2)^2*(1-al)*V;
end
end
  3 Commenti
Victor Jimenez Carrillo
Victor Jimenez Carrillo il 16 Set 2021
My code didn't run, but I rewrote the code on another script and it worked!
Rik
Rik il 16 Set 2021
You also have a function with the same name as a variable.

Accedi per commentare.

Risposte (1)

Voss
Voss il 18 Dic 2021
The reason for the warning "Jac might be unused" is that Jac is initialized and then later overwritten, and it is not used for anything between the time it's initialized and the time it's overwritten.
It is true that Jac is also a variable in a nested function, which ordinarily is seen by the parent function, but in this case Jac is an output argument from the nested function, so the two Jac's are different. That is to say, your thinking would be right (i.e., the warning is mistaken) if Jac were not used as an output argument from the nested function J.
In this case, the warning is correct and initializing Jac to zeros up top has no effect.

Prodotti


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by