# FSOLVE was working until enclosed in a function - difficult for me to interpret error

2 visualizaciones (últimos 30 días)
Paul el 22 de Dic. de 2022
Comentada: Torsten el 22 de Dic. de 2022
This section of code was working fine as part of my main live script but has stopped working since I put it into now part of a function;
Vbv = [(0:0.2:9) (9.2:0.2:9.8) (9.82:0.05:9.97) 10 (10.03:0.05:10.18) (10.2:0.2:10.8) (11:0.5:20)];
options = optimset('Display','off','TolFun',1e-12,'TolX',1e-12);
pHv0 = 2;
for i = 1:numel(Vbv)
fun_actual = @(x)fun(x,Ca1, Va, pKa1, Cb1, pKb) - Vbv(i);
pHv(i) = fsolve(fun_actual,pHv0,options);
pHv0 = pHv(i);
end
Vbv is this function
function Vbv = fun(pHv, Ca, Va, pKa, Cb, pKb)
Kw = 1*10^-14;
Ka = 10^-pKa;
Kb = 10^-pKb;
H = 10^-pHv;
Vbv = Va * ((Ca/(1+H/Ka) - H + Kw/H)/(Cb/(1+Kw/(H*Kb )) + H - Kw/H ));
end
Now that it is part of a function I am getting these errors which I am having difficulty interpreting
The script and associated data are attached - they should be in the same folder/location. Any help will be highly appreciated.
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

Bora Eryilmaz el 22 de Dic. de 2022
Editada: Bora Eryilmaz el 22 de Dic. de 2022
The variable pKb that you pass to the function is not initialized as global and assigned a value, so it is passed as [] to the function. This makes Kb to be empty as well. As a result the computation of Vbv fails.
Actually, on line 48 you have
pKb = 0.2;
It should be
global pKb
pKb = 0.2;
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Torsten el 22 de Dic. de 2022
@Paul comment moved here:
That's absolutely great Bora - many, many thanks.

Iniciar sesión para comentar.

### Categorías

Más información sobre Modeling en Help Center y File Exchange.

R2022b

### Community Treasure Hunt

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

Start Hunting!

Translated by