How to use fsolve when a nonlinear equation given two arrays of parameters (not the variables)? Why can't I use for loop?

1 次查看(过去 30 天)
I want to find osmotic pressure of a solution as follows. Please let me know how I find y(1) values with varying T and P. Thank you.
T=[303 313 323];
P=0:1:10
function Z=osmotic(y)
%y(1)= pi, osmotic pressure [bar]
Cfb=0.05; %[mol/L]
VHF=2;
z=0.0278; [kg.m-2.s-1]
for k=1:length(T)
for j=1:length(P)
Z(1)=y(1)/(VHF*R*T(k))- Cfb*exp(B(1,k)*(Pv((Tf(k)),P(j))-Pv(Tp(k),y(1)))/z);
end
end
end
%Guess osmotic pressure
VHF=2;
Cfb=0.05;
y0=VHF*R*T*Cfb;
%fsolve initiation for osmotic pressure
options=optimset('display','iter');
pi=fsolve(@osmotic,y0,options);

回答(1 个)

Stephan
Stephan 2020-7-30
Hi,
you could try to vectorize your function in order to avoid for loops - here is a simple example:
% Constant 1 as a row vector
T=[10 20 30];
% Constant 2 as a column vector
P=(1:10)';
% Vectorized function to avoid for loop
fun = @(x,T,P) T .* x - P.^2;
% Preallocate x0 with the size of the resulting matrix
x0 = zeros(numel(P),numel(T));
% call fsolve
sol = fsolve(@(x)fun(x,T,P),x0)
% test solutions
should_be_all_near_or_equal_to_zero = fun(sol,T,P)
  1 个评论
Duong Nguyen
Duong Nguyen 2020-7-30
编辑:Duong Nguyen 2020-7-31
I think it works for two constants T and P. Thank you!
But if I have more constants, e.g. Tf, Tp, and B in the following code so can you show me how to do it? (B, Tf, Tp depends on T). I appreciate your help

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Systems of Nonlinear Equations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by