I have a Matlab code that simulates frisbee flight dynamics. I would like to add a wind variable. I did it, but after seeing the plots I think my wind is reducing the speed of the disc. I mean it should change the speed of the disc but via lift and drag force, now it looks like wind speed variable direcly changes disc speed variable. What I want is to affect only the lift and drag forces with wind, but I can't make it work. Here is my current code that is not working. This is an external M-file which is used by the ode45 function in the main script:
[t,x]=ode45(#discfltEOM,tspan,x0,options,CoefUsed);
function xdot=discfltEOM(t,x,CoefUsed)
% Equations of Motion for the frisbee
% The inertial frame, xyz = forward, right and down
global m g Ia Id A d rho
global CLo CLa CDo CDa CMo CMa CRr
global CL_data CD_data CM_data CRr_rad CRr_AdvR CRr_data
global CMq CRp CNr
% x = [ x y z vx vy vz f th fd thd gd gamma Wx Wy]
% 1 2 3 4 5 6 7 8 9 10 11 12 13 14
%% give states normal names
vx = x(4);
vy = x(5);
vz = x(6);
f = x(7);
th = x(8);
st = sin(th);
ct = cos(th);
sf = sin(f);
cf = cos(f);
fd = x(9);
thd= x(10);
gd = x(11);
Wx = x(13);
Wy = x(14);
%% Define transformation matrix
%% [c]=[T_c_N] * [N]
T_c_N=[ct st*sf -st*cf; 0 cf sf; st -ct*sf ct*cf];
%% [d]=[T_d_N] * [N]
%T_d_N(1,:)=[cg*ct sg*cf+sf*st*cg sf*sg-st*cf*cg];
%T_d_N(2,:)=[ -sg*ct cf*cg-sf*sg*st sf*cg+sg*st*cf];
%T_d_N(3,:)=[ st -sf*ct cf*ct]
[evec,eval]=eig(T_c_N);
eigM1=diag(eval);
m1=norm(eigM1(1));
m2=norm(eigM1(2));
m3=norm(eigM1(3));
c1=T_c_N(1,:); % c1 expressed in N frame
c2=T_c_N(2,:); % c2 expressed in N frame
c3=T_c_N(3,:); % c3 expressed in N frame
%% calculate aerodynamic forces and moments
%% every vector is expressed in the N frame
vel = [vx vy vz]; %expressed in N
vmag = norm(vel);
Vwiatr = [Wx Wy 0];
Vw = norm(Vwiatr);
vc3=dot(vel,c3); % velocity (scalar) in the c3 direction
vp= [vel-vc3*c3]; % subtract the c3 velocity component to get the velocity vector
% projected onto the plane of the disc, expressed in N
alpha = atan(vc3/norm(vp));
Adp = A*rho*(vmag-Vw)*(vmag-Vw)/2;
uvel = vel/vmag; % unit vector in vel direction, expressed in N
uvp = vp/norm(vp); % unit vector in the projected velocity direction, expressed in N
ulat = cross(c3,uvp); % unit vec perp to v and d3 that points to right, right?
%% first calc moments in uvp (roll), ulat(pitch) directions, then express in n1,n2,n3
omegaD_N_inC = [fd*ct thd fd*st+gd]; % expressed in c1,c2,c3
omegaD_N_inN = T_c_N'*omegaD_N_inC'; % expressed in n1,n2,n3
omegavp = dot(omegaD_N_inN,uvp);
omegalat = dot(omegaD_N_inN,ulat);
omegaspin = dot(omegaD_N_inN,c3); % omegaspin = p1=fd*st+gd
AdvR= d*omegaspin/2/vmag ; % advanced ration
if CoefUsed==1 % using short flights coefficients
CL = CLo + CLa*alpha;
alphaeq = -CLo/CLa; % this is angle of attack at zero lift
CD = CDo + CDa*(alpha-alphaeq)*(alpha-alphaeq);
CM=CMo + CMa*alpha;
%CRr= CRr*d*omegaspinv/2./vmagv';
%CRr= CRr*sqrt(d/g)*omegaspinv; % this line produces NaN, so leave it in Mvp equation
%Mvp = Adp*d* (CRr*d*omegaspin/2/vmag + CRp*omegavp)*uvp; % expressed in N
Mvp = Adp*d*(sqrt(d/g)*CRr*omegaspin + CRp*omegavp)*uvp; % expressed in N
end % if CoefUsed==1 % using short flights coefficients
if CoefUsed==2 % using potts coefficients
%% interpolation of Potts and Crowther (2002) data
CL = interp1(CL_data(:,1), CL_data(:,2), alpha,'spline');
CD = interp1(CD_data(:,1), CD_data(:,2), alpha,'spline');
CM = interp1(CM_data(:,1), CM_data(:,2), alpha,'spline');
CRr = interp2(CRr_rad,CRr_AdvR,CRr_data,alpha,AdvR,'spline');
Mvp = Adp*d* (CRr* + CRp*omegavp)*uvp; % Roll moment, expressed in N
end % if CoefUsed==2 % using potts coefficients
lift = CL*Adp;
drag = CD*Adp;
ulift = -cross(uvel,ulat); % ulift always has - d3 component
udrag = -uvel;
Faero = lift*ulift + drag*udrag; % aero force in N
FgN = [ 0 0 m*g]'; % gravity force in N
F = Faero' + FgN;
Mlat = Adp*d*(CM + CMq*omegalat)*ulat; % Pitch moment expressed in N
Mspin = [0 0 +CNr*(omegaspin)]; % Spin Down moment expressed in C
M = T_c_N*Mvp' + T_c_N*Mlat' + Mspin'; % Total moment expressed in C
% set moments equal to zero if wanted...
% M=[0 0 0];
% calculate the derivatives of the states
xdot = vel';
xdot(4) = (F(1)/m); %accx
xdot(5) = (F(2)/m); %accy
xdot(6) = (F(3)/m); %accz
xdot(7) = fd;
xdot(8) = thd;
xdot(9) = (M(1) + Id*thd*fd*st - Ia*thd*(fd*st+gd) + Id*thd*fd*st)/Id/ct;
xdot(10) = (M(2) + Ia*fd*ct*(fd*st +gd) - Id*fd*fd*ct*st)/Id;
fdd=xdot(9);
xdot(11) = (M(3) - Ia*(fdd*st + thd*fd*ct))/Ia;
xdot(12) = x(11);
xdot(13) = Wx;
xdot(14) = Wy;
xdott=xdot';
% calculate angular momentum
H = [Id 0 0 ; 0 Id 0; 0 0 Ia]*omegaD_N_inC';
format long;
magH = norm(H);
format short;
state=x';
Wx and Wy are wind vectors. I'm trying to affect the Adp variable because it is direcly connected with lift and drag. I made Wx = 1 [m/s] and the effect is immense, but should be very little. I'm terrible with Matlab so I'm sure I making some kind of stupid mistake from not understanding well how it all works.
Related
Find the error as a function of n, where the error is defined as the difference between two the voltage from the Fourier series (vF (t)) and the value from the ideal function (v(t)), normalized to the maximum magnitude (Vm ):
I am given this prompt where Vm = 1 V. Below this line is the code which I have written.
I am trying to write a function to solve this question: Plot the error versus time for n=3,n=5,n=10, and n=50. (10points). What does it look like I am doing incorrectly?
clc;
close all;
clear all;
% define the signal parameters
Vm = 1;
T = 1;
w0 = 2*pi/T;
% define the symbolic variables
syms n t;
% define the signal
v1 = Vm*sin(4*pi*t/T);
v2 = 2*Vm*sin(4*pi*t/T);
% evaluate the fourier series integral
an1 = 2/T*int(v1*cos(n*w0*t),0,T/2) + 2/T*int(v2*cos(n*w0*t),T/2,T);
bn1 = 2/T*int(v1*sin(n*w0*t),0,T/2) + 2/T*int(v2*sin(n*w0*t),T/2,T);
a0 = 1/T*int(v1,0,T/2) + 1/T*int(v2,T/2,T);
% obtain C by substituting n in c[n]
nmax = 100;
n = 1:nmax;
a = subs(an1);
b = subs(bn1);
% define the time vector
ts = 1e-2; % ts is sampling the
t = 0:ts:3*T-ts;
% directly plot the signal x(t)
t1 = 0:ts:T-ts;
v1 = Vm*sin(4*pi*t1/T).*(t1<=T/2);
v2 = 2*Vm*sin(4*pi*t1/T).*(t1>T/2).*(t1<T);
v = v1+v2;
x = repmat(v,1,3);
% Now fourier series reconstruction
N = [3];
for p = 1:length(N)
for i = 1:length(t)
for k = N(p)
x(k,i) = a(k)*cos(k*w0*t(i)) + b(k)*sin(k*w0*t(i));
end
% y(k,i) = a0+sum(x(:,i)); % Add DC term
end
end
z = a0 + sum(x);
figure(1);
plot(t,z);
%Percent error
function [per_error] = percent_error(measured, actual)
per_error = abs(( (measured - actual) ./ 1) * 100);
end
The purpose of the forum is helping with specific technical questions, not doing your homework.
I've had problems with my code as I've tried to make an integral compute, but it will not for the power, P2.
I've tried using anonymous function handles to use the integral() function on MATLAB as well as just using int(), but it will still not compute. Are the values too small for MATLAB to integrate or am I just missing something small?
Any help or advice would be appreciated to push me in the right direction. Thanks!
The problem in the code is in the bottom of the section labelled "Power Calculations". My integral also gets quite messy if that makes a difference.
%%%%%%%%%%% Parameters %%%%%%%%%%%%
n0 = 1; %air
n1 = 1.4; %layer 1
n2 = 2.62; %layer 2
n3 = 3.5; %silicon
L0 = 650*10^(-9); %centre wavelength
L1 = 200*10^(-9): 10*10^(-9): 2200*10^(-9); %lambda from 200nm to 2200nm
x = ((pi./2).*(L0./L1)); %layer phase thickness
r01 = ((n0 - n1)./(n0 + n1)); %reflection coefficient 01
r12 = ((n1 - n2)./(n1 + n2)); %reflection coefficient 12
r23 = ((n2 - n3)./(n2 + n3)); %reflection coefficient 23
t01 = ((2.*n0)./(n0 + n1)); %transmission coefficient 01
t12 = ((2.*n1)./(n1 + n2)); %transmission coefficient 12
t23 = ((2.*n2)./(n2 + n3)); %transmission coefficient 23
Q1 = [1 r01; r01 1]; %Matrix Q1
Q2 = [1 r12; r12 1]; %Matrix Q2
Q3 = [1 r23; r23 1]; %Matrix Q3
%%%%%%%%%%%% Graph of L vs R %%%%%%%%%%%
R = zeros(size(x));
for i = 1:length(x)
P = [exp(j.*x(i)) 0; 0 exp(-j.*x(i))]; %General Matrix P
T = ((1./(t01.*t12.*t23)).*(Q1*P*Q2*P*Q3)); %Transmission
T11 = T(1,1); %T11 value
T21 = T(2,1); %T21 value
R(i) = ((abs(T21./T11))^2).*100; %Percent reflectivity
end
plot(L1,R)
title('Percent Reflectance vs. wavelength for 2 Layers')
xlabel('Wavelength (m)')
ylabel('Reflectance (%)')
%%%%%%%%%%% Power Calculation %%%%%%%%%%
syms L; %General lamda
y = ((pi./2).*(L0./L)); %Layer phase thickness with variable Lamda
P1 = [exp(j.*y) 0; 0 exp(-j.*y)]; %Matrix P with variable Lambda
T1 = ((1./(t01.*t12.*t23)).*(Q1*P1*Q2*P1*Q3)); %Transmittivity matrix T1
I = ((6.16^(15))./((L.^(5)).*exp(2484./L) - 1)); %Blackbody Irradiance
Tf11 = T1(1,1); %New T11 section of matrix with variable Lambda
Tf2 = (((abs(1./Tf11))^2).*(n3./n0)); %final transmittivity
P1 = Tf2.*I; %Power before integration
L_initial = 200*10^(-9); %Initial wavelength
L_final = 2200*10^(-9); %Final wavelength
P2 = int(P1, L, L_initial, L_final) %Power production
I've refactored your code
to make it easier to read
to improve code reuse
to improve performance
to make it easier to understand
Why do you use so many unnecessary parentheses?!
Anyway, there's a few problems I saw in your code.
You used i as a loop variable, and j as the imaginary unit. It was OK for this one instance, but just barely so. In the future it's better to use 1i or 1j for the imaginary unit, and/or m or ii or something other than i or j as the loop index variable. You're helping yourself and your colleagues; it's just less confusing that way.
Towards the end, you used the variable name P1 twice in a row, and in two different ways. Although it works here, it's confusing! Took me a while to unravel why a matrix-producing function was producing scalars instead...
But by far the biggest problem in your code is the numerical problems with the blackbody irradiance computation. The term
L⁵ · exp(2484/L) - 1
for λ₀ = 200 · 10⁻⁹ m will require computing the quantity
exp(1.242 · 10¹⁰)
which, needless to say, is rather difficult for a computer :) Actually, the problem with your computation is two-fold. First, the exponentiation is definitely out of range of 64 bit IEEE-754 double precision, and will therefore result in ∞. Second, the parentheses are wrong; Planck's law should read
C/L⁵ · 1/(exp(D) - 1)
with C and D the constants (involving Planck's constant, speed of light, and Boltzmann constant), which you've presumably precomputed (I didn't check the values. I do know choice of units can mess these up, so better check).
So, aside from the silly parentheses error, I suspect the main problem is that you simply forgot to rescale λ to nm. Changing everything in the blackbody equation to nm and correcting those parentheses gives the code
I = 6.16^(15) / ( (L*1e+9)^5 * (exp(2484/(L*1e+9)) - 1) );
With this, I got a finite value for the integral of
P2 = 1.052916498836486e-010
But, again, you'd better double-check everything.
Note that I used quadgk(), because it's one of the better ones available on R2010a (which I'm stuck with), but you can just as easily replace this with integral() available on anything newer than R2012a.
Here's the code I ended up with:
function pwr = my_fcn()
% Parameters
n0 = 1; % air
n1 = 1.4; % layer 1
n2 = 2.62; % layer 2
n3 = 3.5; % silicon
L0 = 650e-9; % centre wavelength
% Reflection coefficients
r01 = (n0 - n1)/(n0 + n1);
r12 = (n1 - n2)/(n1 + n2);
r23 = (n2 - n3)/(n2 + n3);
% Transmission coefficients
t01 = (2*n0) / (n0 + n1);
t12 = (2*n1) / (n1 + n2);
t23 = (2*n2) / (n2 + n3);
% Quality factors
Q1 = [1 r01; r01 1];
Q2 = [1 r12; r12 1];
Q3 = [1 r23; r23 1];
% Initial & Final wavelengths
L_initial = 200e-9;
L_final = 2200e-9;
% plot reflectivity for selected lambda range
plot_reflectivity(L_initial, L_final, 1000);
% Compute power production
pwr = quadgk(#power_production, L_initial, L_final);
% Helper functions
% ========================================
% Graph of lambda vs reflectivity
function plot_reflectivity(L_initial, L_final, N)
L = linspace(L_initial, L_final, N);
R = zeros(size(L));
for ii = 1:numel(L)
% Transmission
T = transmittivity(L(ii));
% Percent reflectivity
R(ii) = 100 * abs(T(2,1)/T(1,1))^2 ;
end
plot(L, R)
title('Percent Reflectance vs. wavelength for 2 Layers')
xlabel('Wavelength (m)')
ylabel('Reflectance (%)')
end
% Compute transmittivity matrix for a single wavelength
function T = transmittivity(L)
% Layer phase thickness with variable Lamda
y = pi/2 * L0/L;
% Matrix P with variable Lambda
P1 = [exp(+1j*y) 0
0 exp(-1j*y)];
% Transmittivity matrix T1
T = 1/(t01*t12*t23) * Q1*P1*Q2*P1*Q3;
end
% Power for a specific wavelength. Note that this function
% accepts vector-valued wavelengths; needed for quadgk()
function pwr = power_production(L)
pwr = zeros(size(L));
for ii = 1:numel(L)
% Transmittivity matrix
T1 = transmittivity(L(ii));
% Blackbody Irradiance
I = 6.16^(15) / ( (L(ii)*1e+9)^5 * (exp(2484/(L(ii)*1e+9)) - 1) );
% final transmittivity
Tf2 = abs(1/T1(1))^2 * n3/n0;
% Power before integration
pwr(ii) = Tf2 * I;
end
end
end
In this MATLAB code, I intend to display a graph, but it shows me an empty graph.
% Proposed Model For Two-Phase Flow Analytical Design Equation for gas
% pipelines
clc
d = 26.75; % diameter in inches
pie = 3.142; %normal pie
A = (pie *d^2)/4; % Compute for the area
qm = 150; %volume flow rate of mixture
pm = 8; %Density of the mixture
Wm = qm* pm; % mass flow rate of mixture i.e oil and gas
Ho = 0.01; %Liquid Hold up
z = 0.85; % compressibility factor
R = 10.73; % Gas constant
f = 0.0254; %friction factor
p0 = 150; % Density of oil
T = 580; % Temperature in R degrees
P0 =1700; % 1700psi
L = 63.068; % Length
P1 = 602.7; % 602.7 psia
%Assume
Mg = 9.8;
formule1 = d*A^2*Mg*(1-Ho);
formule2 = f*Wm^2*z*R*T;
formule = formule1/formule2;
exprs1 = (p0*Ho*z*R*T)/Mg*(1-Ho);
express2 = P2^2-P1^2
drop_p =P1-P2
express3 = 2*p0*Ho*z*R*T*drop_p
better_express = express2 + express3
func1 = d/f
solve( (formule*better_express)- func1*log(P2+ exprs1/P1 + exprs1)^2 + L == 0, P2)
figure
plot(drop_p,L,'r:+')
Please, can anyone help me out? Thanks.
In your code: drop_p = P1-P2 and L = 63.068, so unless P2 is a vector you will get just a single red + in your graph. Like this (for P2 = 1):
Right now, the solve line returns an error, because it should be with '' on the variable to solve to:
solve( (formule*better_express)- func1*log(P2+ exprs1/P1 + exprs1)^2 + L == 0, 'P2')
but this doesn't effect the resulted graph anyway, because the solve output is not assigned to any variable.
In my matlab program:
% Orto-xylene oxidation in an adiabatic PFR.
% ethylbenzene -> Anhydrated-xylene + H2
% There is water as an inert in the system
global y0 F0 deltaHR0 P0 ni n
y0(1) = 0.0769; % ethylbenzene
y0(2) = 0.; % styrene
y0(3) = 0.; % hydrogen
y0(4) = 0.923; % water
Feed = 1105.; % F01 + FH2O Feed rate [mol/s]
F0 = Feed .* y0; % Inlet feed rate of components [mol/s]
Tin = 925.;
n = 4.; % Number of reacting compound
deltaHR0 = 124850.; % heat of reaction at standard conditions[J/mol]
P0 = 240000.; % pressure [Pa]
W = 25400.; % reactor weight [kg]
ni = [-1 1 1 0]; % Stoichiometric matrix
% Initial conditions (feed and T0)
u0 = F0;
u0(n+1) = Tin;
wspan = [0 W];
[w_adiab,u] = ode15s(#dfuns,wspan,u0);
conv_adiab = 1 - u(:,1)/F0(1);
T = u(:,n+1);
subplot(2,1,1)
plot(w_adiab,conv_adiab,'-')
title('Conversion profile')
grid on
xlabel('W')
ylabel('X(A1)')
subplot(2,1,2)
plot(w_adiab,T,'-')
title('Temperature profile')
grid on
xlabel('W')
ylabel('T')
%function file dfuns
function f = dfuns (w,U)
global y0 F0 deltaHR0 P0 ni n
% U(1) = F1
% U(2) = F2
% U(3) = F3
% U(4) = F4
% y is a vector of n components
y = U(1:n)/sum(U(1:n)); % molar fractions
T = U(n+1);
k = 3.46* 10e8.* exp(-10980./T); %Needs to be in Pascal
K = 8.2.* 10e11.* exp(-15200./T); %Needs to be in Pascal
rm = k.* (y(1)* P0- (y(2).* y(3).*(P0^2))./ K);
f(1:n) = -ni(1:n).* rm;
Cp1 = 37.778 + 87.940e-3.* T + 113.436e-5.* T^2; % ethylbenzene
%Cp2 = 71.201 + 54.706e-3.* T + 64.791e-5.* T^2; % styrene
%Cp3 = 23.969 + 30.603e-3.*T - 6.418e-5.* T^2; % hydrogen
Cp4 = 36.540 - 34.827e-3.*T + 11.681e-5.*T^2; % water
deltaCp = 0.;
% deltaCp considered to be different from zero
% deltaCp = -Cp1+Cp2+Cp3;
deltaHR = deltaHR0;
% non-const deltaHR
% T0=273.5;
% deltaHR = - deltaHR0 + (37.778.* T + 87.940e-3.* (T^2)./2 +...
% 113.436e-5.* (T^3)./3) + (71.201.* T + 54.706e-3.* (T^2)./2 + ...
% 64.791e-5.* (T^3)/3) + (23.969.*T + 30.603e-3.* (T^2)./2 -...
% 6.418e-5.* (T^3)/3) - (37.778*T0 - ...
% 87.940e-3.*(T0^2)./2 + 113.436e-5.* (T0^3)./3 )+...
% (71.201 * T0 + 54.706e-3.* (T0^2)./2 + 64.791e-5.* ...
% (T0^3)./3) + (23.969 * T0 + 30.603e-3.* (T0^2)./2 -...
% 6.418e-5.* (T0^3)./3);
f(n+1) = (1./((F0(1)+F0(4)).* (y0(1).* Cp1 + y0(4).* Cp4 +y(1).* deltaCp)*...
(1 - U(1)/F0(1)))).*-deltaHR.* rm;
f = f'; % transformation to column vector
I have a problem because of the forrowing warning:
In catPFR (line 21)
Warning: Matrix is singular, close to singular or badly scaled. Results may be inaccurate. RCOND = NaN.
> In ode15s (line 589)
In catPFR (line 21)
Warning: Failure at t=0.000000e+00. Unable to meet integration tolerances without reducing the step size below the
smallest value allowed (7.905050e-323) at time t.
> In ode15s (line 668)
In catPFR (line 21)
Can please someone help me? This problem could be a error in the function but I'm really not into matlab enough to understand it. Of course, I don't get the graph I was expecting.
Thank you very much,
Serena
If you inspect return values of function dfuns (w,U) during the integration, you will see that in most cases it contains NaN's or Inf's. Of course ode15s cannot proceed in this case. Check dfuns and assure that it returns correct values.
I am trying to give a/set 'rho_real' to this code and receive P_Mpa as an/set of outputs, however the initial 'rho_real' does not seem to get changed as I run the function.
Any Help is greatly appreciated.
function P_Mpa = Density_vs_Pressure_Ethane (rho_real)
% calculating Pressure vs Density curve using
mi = [1.6069,1.6069];
sigmai = [3.5206,3.5206]; 1
% epsilon = [2.873268218e-21,2.873268218e-21];
epsilon_ki = [191.42,191.42];
xi = [0.5,0.5]; % mole fraction of component i
T = 298.15; % temperature of the system
% k_bolt = 1.3806488e-23; % Boltzmann constant = 1.3806488 × 10-23 m2 kg s-2 K-1
% Initial guess for density
rho_real = 10000;
rho = rho_real*6.022e-7;
% Initial Kij
Kij = 0;
% Temperatuure-dependent segment diameter di of component i - matrix save
di = zeros(1,2);
giihs = zeros (1,2);
rho_giihs = zeros (1,2);
m_bar = 0;
zi0=0;
zi1=0;
zi2=0;
zi3=0;
for i=1:2
m_bar=m_bar+((xi(1,i))*(mi(1,i)));
di(1,i) = (sigmai(1,i))*(1-(0.12*exp(-3*(epsilon_ki(1,i))/T)));
% Calculating Zieeeeeeh for Hard Sphere compressibility (Rechcecked)
zi0 = zi0+((pi/6)*rho)*(xi(1,i)*(mi(1,i))*((di(1,i))^0));
zi1 = zi1+((pi/6)*rho)*(xi(1,i)*(mi(1,i))*((di(1,i))^1));
zi2 = zi2+((pi/6)*rho)*(xi(1,i)*(mi(1,i))*((di(1,i))^2));
zi3 = zi3+((pi/6)*rho)*(xi(1,i)*(mi(1,i))*((di(1,i))^3));
end
for i=1:2
giihs (1,i)= (1/(1-zi3))+((((di(1,i))^2)/(2*(di(1,i))))*(3*zi2)/((1-zi3)^2))+((di(1,i)^2)/(2*(di(1,i)^2))^2)*((2*(zi2)^2)/((1-zi3)^3));
% Derevative of site to site radial distribution function of hard spheres
% with respect to density
rho_giihs (1,i) = ((zi3/((1-zi3)^2)))+(((((di(1,i))^2)/(2*(di(1,i)))))*...
((((3*zi2)/((1-zi3)^2)))+((6*zi2*zi3)/((1-zi3)^3))))+...
(((((di(1,i))^2)/(2*(di(1,i))))^2)*(((4*(zi2^2))/((1-zi3)^3))+...
(((6*zi2^2)*zi3)/((1-zi3)^4))));
end
eta = zi3;
% Calculating the hard sphere compresibility factor ( Rechecked)
zhs = (zi3/(1-zi3)+((3*zi1*zi2)/((zi0*(1-zi3)^2)))+(((3*(zi2^3))-(zi3*(zi2^3)))/(zi0*((1-(zi3)^3)))));
zhc=0;
for i = 1:2
% Calculating the hard chain compressibility factor (Rechecked)
zhc= zhc+((xi(1,i)*(mi(1,i)-1)*((giihs(1,i))^-1)*((rho_giihs(1,i)))));
end
zhc=m_bar*zhs-zhc;
% a0 constants
a0 = [0.9105631445,0.6361281449,2.6861347891,-26.547362491,97.759208784,-159.59154087,91.297774084]; % Checked and Correct Sadowski 2001
% a1 constants
a1 = [-0.3084016918,0.1860531159,-2.5030047259,21.419793629,-65.255885330,83.318680481,-33.746922930]; % Checked and Correct Sadowski 2001
% a2 constants
a2 = [-0.0906148351,0.4527842806,0.5962700728,-1.7241829131,-4.1302112531,13.776631870,-8.6728470368]; % Checked and Correct Sadowski 2001
% b0 constants
b0 = [0.7240946941,2.2382791861,-4.0025849485,-21.003576815,26.855641363,206.55133841,-355.60235612]; % Checked and Correct Sadowski 2001
% b1 constants
b1 = [-0.5755498075,0.6995095521,3.8925673390,-17.215471648,192.67226447,-161.82646165,-165.20769346]; % Checked and Correct Sadowski 2001
% b2 constants
b2 = [0.0976883116,-0.2557574982,-9.1558561530,20.642075974,-38.804430052,93.626774077,-29.666905585];
aim = zeros(1,7);
bim = zeros(1,7);
for i = 1:7
aim(1,i)=a0(1,i)+(((m_bar-1)/m_bar)*a1(1,i))+(((m_bar-1)/m_bar)*((m_bar-2)/m_bar))*a2(1,i); % Checked and Correct Sadowski 2001 (rechecked)
bim(1,i)=b0(1,i)+(((m_bar-1)/m_bar)*b1(1,i))+(((m_bar-1)/m_bar)*((m_bar-2)/m_bar))*b2(1,i);
c1 = ((1 + (m_bar*(((8*eta)-(2*eta^2))/(1-eta)^4)+((1-m_bar)*(((20*eta)-(27*eta^2)+(12*eta^3)-(2*eta^4))/(((1-eta)*(2-eta))^2)))))^-1);
c2 = ((-c1^2)*(m_bar*(((-4*eta^2)+(20*eta)+8)/((1-eta)^5))+((1-m_bar)*(((2*eta^3)+(12*eta^2)-(48*eta)+40)/(((1-eta)*(2-eta))^3)))));
% Integrals of perturbation theory without/with respect to eta (rechecked)
dI1 = 0;
dI2 = 0;
I1 = 0;
I2 = 0;
for j = 1:7
I1 = I1+ aim(1,j)*eta^(j-1);
I2 = I2+ bim(1,j)*eta^(j-1);
dI1 = dI1 + (aim(1,j)*((j-1)+1)*(eta^(j-1)));
dI2 = dI2 + (bim(1,j)*((j-1)+1)*(eta^(j-1)));
end
% Segment abriviations
m2e = 0;
m2e2 = 0;
sigma_ij = zeros(1,2);
epsilon_ij = zeros (1,2);
for i = 1:2
for j = 1:2
% Mixing rules for sigma and eta respectively.
sigma_ij(i,j)=0.5*(sigmai(1,i)+sigmai(1,j));
epsilon_ij(i,j)=sqrt((epsilon_ki(1,i)*epsilon_ki(1,j))*(1-Kij));
m2e=m2e+(xi(1,i)*xi(1,j)*mi(1,i)*mi(1,j)*((epsilon_ij(i,j)/(T)))*(sigma_ij(i,j)^3));
m2e2=m2e2+(xi(1,i)*xi(1,j)*mi(1,i)*mi(1,j)*(((epsilon_ij(i,j)/(T)))^2)*(sigma_ij(i,j)^3));
end
end
% The dispersion contribution to the comprehensibility factor
zdis = (-2*pi*rho*dI1*m2e)-(pi*rho*m_bar*((c1*dI2)+(c2*eta*I2))*m2e2);
% Compresibility Factor (rechecked)
z = 1 + zhc + zdis;
zdis;
zhc;
P = z*8.314*T*rho/6.022e-7; % (rechecked)
P_Mpa = P*1e-6;
In the line below % Initial guess for density: you set the value of rho_real to 10000. From then on, of course, rho_real will be 10000 no matter what the input argument was. If you remove this line, your function will behave as your script, with variable rho_real defined by the input argument.
MATLAB does have a way of providing default values for arguments. Your function could test how many arguments were provided. If rho_real was left out, i.e. if the number of arguments nargin is less than 1, only then you set rho_real.
if nargin < 1
rho_real = 10000
end