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

1 view (last 30 days)
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);

Answers (1)

Stephan
Stephan on 30 Jul 2020
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 Comment
Duong Nguyen
Duong Nguyen on 30 Jul 2020
Edited: Duong Nguyen on 31 Jul 2020
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

Sign in to comment.

Categories

Find more on Systems of Nonlinear Equations in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!