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
Related
The following code uses rk4 to simulate the dynamics defined via fe function. However, I encountered the warning Warning: Matrix is singular, close to singular or badly scaled. Results may be inaccurate. RCOND = NaN. .
I felt that the function defined in fe, sometimes the Numerator equals zero, thus creates singularity. But I don't know how to avoid it.
Should I change the function formula (I prefer not to), or should I revise the code, or change the solver?
Thank you in advance for any suggestion.
clear;
global G
tic
n=40;
A = ones(n) - eye(n);
G = graph(A);
num_samples =1;
p.G = A
dim_G = size(p.G);
p.K = 1;
p.N = dim_G(1);
nIters = 2000;
tBegin = 0;
tEnd = 100;
% initial condition
Init = -pi + 2*pi.*rand(p.N,num_samples);
dim_thetaInit = size(Init);
Init = Init(:,1);
[t,sol] = rk4(#fe,tBegin,tEnd,Init,nIters,p);
function td = fe(t,theta,p)
[theta_i,theta_j] = meshgrid(theta);
adj_matrix = p.G;
a = 4;
b = 1;
td= sum(adj_matrix'.*( ( b*cos(theta_i-theta_j) * (2*a^2*cos(theta_i-theta_j)*sin(theta_i-theta_j)-2*b^2*cos(theta_i-theta_j)*sin(theta_i-theta_j)) ) / ( 2*(b^2*(cos(theta_i-theta_j))^2+a^2*(sin(theta_i-theta_j))^2)^(3/2) ) + (b*sin(theta_i-theta_j))/( sqrt( b^2*cos(theta_i-theta_j)^2 + a^2*sin(theta_i-theta_j)^2 ) ) ),1)';
end
function [T,Y] = rk4(f,a,b,ya,m,p)
%---------------------------------------------------------------------------
% RK4 Runge-Kutta solution for y' = f(t,y) with y(a) = ya .
% Sample call
% [T,Y] = rk4('f',a,b,ya,m)
% Inputs
% f name of the function
% a left endpoint of [a,b]
% b right endpoint of [a,b]
% ya initial value
% m number of steps
% p Kuramoto function arguments
% Return
% T solution: vector of abscissas
% Y solution: vector of ordinates
%
% NUMERICAL METHODS: MATLAB Programs, (c) John H . Mathews 1995
% To accompany the text:
% NUMERICAL METHODS for Mathematics, Science and Engineering, 2nd Ed, 1992
% Prentice Hall, Englewood Cliffs, New Jersey, 07632, U . S . A .
% Prentice Hall, Inc .; USA, Canada, Mexico ISBN 0-13-624990-6
% Prentice Hall, International Editions: ISBN 0-13-625047-5
% This free software is compliments of the author .
% E-mail address: in % "mathews#fullerton.edu"
%
% Algorithm 9.4 (Runge-Kutta Method of Order 4) .
% Section 9.5, Runge-Kutta Methods, Page 460
%---------------------------------------------------------------------------
h = (b - a)/m;
T = zeros(1,m+1);
size(ya,1)
Y = zeros(size(ya,1),m+1);
T(1) = a;
Y(:,1) = ya;
for j=1:m
tj = T(j);
yj = Y(:,j);
k1 = h*feval(f,tj,yj,p);
k2 = h*feval(f,tj+h/2,yj+k1/2,p);
k3 = h*feval(f,tj+h/2,yj+k2/2,p);
k4 = h*feval(f,tj+h,yj+k3,p);
Y(:,j+1) = yj + (k1 + 2*k2 + 2*k3 + k4)/6;
T(j+1) = a + h*j;
end
end
I am trying to estimate regression and AR parameters for (loads of) linear regressions with AR error terms. (You could also think of this as a MA process with exogenous variables):
, where
, with lags of length p
I am following the official matlab recommendations and use regArima to set up a number of regressions and extract regression and AR parameters (see reproducible example below).
The problem: regArima is slow! For 5 regressions, matlab needs 14.24sec. And I intend to run a large number of different regression models. Is there any quicker method around?
y = rand(100,1);
r2 = rand(100,1);
r3 = rand(100,1);
r4 = rand(100,1);
r5 = rand(100,1);
exo = [r2 r3 r4 r5];
tic
for p = 0:4
Mdl = regARIMA(3,0,0);
[EstMdl, ~, LogL] = estimate(Mdl,y,'X',exo,'Display','off');
end
toc
Unlike the regArima function which uses Maximum Likelihood, the Cochrane-Orcutt prodecure relies on an iteration of OLS regression. There are a few more particularities when this approach is valid (refer to the link posted). But for the aim of this question, the appraoch is valid, and fast!
I modified James Le Sage's code which covers only AR lags of order 1, to cover lags of order p.
function result = olsc(y,x,arterms)
% PURPOSE: computes Cochrane-Orcutt ols Regression for AR1 errors
%---------------------------------------------------
% USAGE: results = olsc(y,x)
% where: y = dependent variable vector (nobs x 1)
% x = independent variables matrix (nobs x nvar)
%---------------------------------------------------
% RETURNS: a structure
% results.meth = 'olsc'
% results.beta = bhat estimates
% results.rho = rho estimate
% results.tstat = t-stats
% results.trho = t-statistic for rho estimate
% results.yhat = yhat
% results.resid = residuals
% results.sige = e'*e/(n-k)
% results.rsqr = rsquared
% results.rbar = rbar-squared
% results.iter = niter x 3 matrix of [rho converg iteration#]
% results.nobs = nobs
% results.nvar = nvars
% results.y = y data vector
% --------------------------------------------------
% SEE ALSO: prt_reg(results), plt_reg(results)
%---------------------------------------------------
% written by:
% James P. LeSage, Dept of Economics
% University of Toledo
% 2801 W. Bancroft St,
% Toledo, OH 43606
% jpl#jpl.econ.utoledo.edu
% do error checking on inputs
if (nargin ~= 3); error('Wrong # of arguments to olsc'); end;
[nobs nvar] = size(x);
[nobs2 junk] = size(y);
if (nobs ~= nobs2); error('x and y must have same # obs in olsc'); end;
% ----- setup parameters
ITERMAX = 100;
converg = 1.0;
rho = zeros(arterms,1);
iter = 1;
% xtmp = lag(x,1);
% ytmp = lag(y,1);
% truncate 1st observation to feed the lag
% xlag = x(1:nobs-1,:);
% ylag = y(1:nobs-1,1);
yt = y(1+arterms:nobs,1);
xt = x(1+arterms:nobs,:);
xlag = zeros(nobs-arterms,arterms);
for tt = 1 : arterms
xlag(:,nvar*(tt-1)+1:nvar*(tt-1)+nvar) = x(arterms-tt+1:nobs-tt,:);
end
ylag = zeros(nobs-arterms,arterms);
for tt = 1 : arterms
ylag(:,tt) = y(arterms-tt+1:nobs-tt,:);
end
% setup storage for iteration results
iterout = zeros(ITERMAX,3);
while (converg > 0.0001) & (iter < ITERMAX),
% step 1, using intial rho = 0, do OLS to get bhat
ystar = yt - ylag*rho;
xstar = zeros(nobs-arterms,nvar);
for ii = 1 : nvar
tmp = zeros(1,arterms);
for tt = 1:arterms
tmp(1,tt)=ii+nvar*(tt-1);
end
xstar(:,ii) = xt(:,ii) - xlag(:,tmp)*rho;
end
beta = (xstar'*xstar)\xstar' * ystar;
e = y - x*beta;
% truncate 1st observation to account for the lag
et = e(1+arterms:nobs,1);
elagt = zeros(nobs-arterms,arterms);
for tt = 1 : arterms
elagt(:,tt) = e(arterms-tt+1:nobs-tt,:);
end
% step 2, update estimate of rho using residuals
% from step 1
res_rho = (elagt'*elagt)\elagt' * et;
rho_last = rho;
rho = res_rho;
converg = sum(abs(rho - rho_last));
% iterout(iter,1) = rho;
iterout(iter,2) = converg;
iterout(iter,3) = iter;
iter = iter + 1;
end; % end of while loop
if iter == ITERMAX
% error('ols_corc did not converge in 100 iterations');
print('ols_corc did not converge in 100 iterations');
end;
result.iter= iterout(1:iter-1,:);
% after convergence produce a final set of estimates using rho-value
ystar = yt - ylag*rho;
xstar = zeros(nobs-arterms,nvar);
for ii = 1 : nvar
tmp = zeros(1,arterms);
for tt = 1:arterms
tmp(1,tt)=ii+nvar*(tt-1);
end
xstar(:,ii) = xt(:,ii) - xlag(:,tmp)*rho;
end
result.beta = (xstar'*xstar)\xstar' * ystar;
e = y - x*result.beta;
et = e(1+arterms:nobs,1);
elagt = zeros(nobs-arterms,arterms);
for tt = 1 : arterms
elagt(:,tt) = e(arterms-tt+1:nobs-tt,:);
end
u = et - elagt*rho;
result.vare = std(u)^2;
result.meth = 'olsc';
result.rho = rho;
result.iter = iterout(1:iter-1,:);
% % compute t-statistic for rho
% varrho = (1-rho*rho)/(nobs-2);
% result.trho = rho/sqrt(varrho);
(I did not adapt in the last 2 lines the t-test for rho vectors of length p, but this should be straight forward to do..)
I've attempted to run this code multiple times and have had zero luck since I added in the last for loop. Before the error, the vector k wouldn't update so the vector L was the same number repeated.
I can't figure out why I am getting the 'Not enough input arguments' error when it was working fine beforehand.
Any help would be much appreciated!
% Set up parameters of the functions
omega = 2*pi/10; % 1/s
g = 9.81; % m/s^2
h = 20; % m
parms = [omega, g, h];
% Set up the root finding variables
etol = 1e-6; % convergence criteria
iter = 100; % maximum number of iterations
f = #my_fun; % function pointer to my_func
fp = #my_fprime; % function pointer to my_fprime
k0 = kguess(parms); % initial guess for root
% Find the root
[k, error, n_iterations] = newtraph(f, fp, k0, etol, iter, parms);
% Get the wavelength
if n_iterations < iter
% Converged correctly
L = 2 * pi / k;
else
% Did not converge
disp('ERROR: Maximum number of iterations exceeded')
return
end
wave = load('wavedata.dat');
dt = 0.04; %s
%dh = 0.234; %water depth in meters
wave = wave*.01; %covnverts from meters to cm
nw = wave([926:25501],1);
a = length(nw);
t = 0;
spot = 1;
points = zeros(1,100);
for i = 1:a-1
t=t+dt;
if nw(i) < 0
if nw(i+1) > 0
points(spot)=t;
spot=spot+1;
t=0;
end
end
end
omega = 2*pi./points; %w
l = length(points);
L = zeros(1,509);
k = zeros(1,509);
for j = 1:l
g = 9.81; % m/s^2
h = 0.234; % m
parms = [omega(j), g, h];
% Set up the root finding variables
etol = 1e-6; % convergence criteria
iter = 100; % maximum number of iterations
f = #my_fun; % function pointer to my_func
fp = #my_fprime; % function pointer to my_fprime
k0(j) = kguess(parms); % initial guess for root
% Find the root
[k(j), error, n_iterations] = newtraph(f, fp, k0(j), etol, iter, parms);
% Get the wavelength
if n_iterations < iter
% Converged correctly
L(j) = 2 * pi / k(j);
else
% Did not converge
disp('ERROR: Maximum number of iterations exceeded')
return
end
end
function [ f ] = my_fun(k,parms)
%MY_FUN creates a function handle for linear dispersion
% Detailed explanation goes here
w = parms(1) ;
g = parms(2);
h = parms(3);
f = g*k*tanh(k*h)-(w^2);
end
function [ fp ] = my_fprime(k,parms)
%MY_FPRIME creates a function handle for first derivative of linear
% dispersion.
g = parms(2);
h = parms(3);
% w = 2*pi/10; % 1/s
% g = 9.81; % m/s^2
% h = 20; % m
fp = g*(k*h*((sech(k*h)).^2) + tanh(k*h));
end
function [ k, error, n_iterations ] = newtraph( f, fp, k0, etol, iterA, parms )
%NEWTRAPH Estimates the value of k using the newton raphson method.
if nargin<3,error('at least 3 input arguments required'),end
if nargin<4|isempty(etol),es=etol;end
if nargin<5|isempty(iterA),maxit=iterA;end
iter = 0;
k = k0;
%func =#f;
%dfunc =#fp;
while (1)
xrold = k;
k = k - f(k)/fp(k);
iter = iter + 1;
if k ~= 0, ea = abs((k - xrold)/k) * 100; end
if ea <= etol | iter >= iterA, break, end
end
error = ea;
n_iterations = iter;
end
In function newtraph at line 106 (second line in the while(1) loop), you forgot to pass parms to the function call f:
k = k - f(k)/fp(k);
should become
k = k - f(k,parms)/fp(k,parms);
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.
I got this code for LARS but when I run, it says undefined X. I can't understand what x is. Why is there an error?
function [beta, A, mu, C, c, gamma] = lars(X, Y, option, t, standardize)
% Least Angle Regression (LAR) algorithm.
% Ref: Efron et. al. (2004) Least angle regression. Annals of Statistics.
% option = 'lar' implements the vanilla LAR algorithm (default);
% option = 'lasso' solves the lasso path with a modified LAR algorithm.
% t -- a vector of increasing positive real numbers. If given, LARS
% returns the solution at t.
%
% Output:
% A -- a sequence of indices that indicate the order of variable
% beta: history of estimated LARS coefficients;
% mu -- history of estimated mean vector;
% C -- history of maximal current absolute corrrelations;
% c -- history of current corrrelations;
% gamma: history of LARS step size.
% Note: history is traced by rows. If t is given, beta is just the
% estimated coefficient vector at the constraint ||beta||_1 = t.
%
% Remarks:
% 1. LARS is originally proposed to estimate a sparse coefficient vector
% a noisy over-determined linear system. LARS outputs estimates for all
% shrinkage/constraint parameters (homotopy).
%
% 2. LARS is well suited for Basis Pursuit (BP) purpose in the real
% automatically terminates when the current correlations for inactive
% all zeros. The recovered coefficient vector is the last column of beta
% with the *lasso* option. Hence, this function provides a fast and
% efficient solution for the ell_1 minimization problem.
% Ref: Donoho and Tsaig (2006). Fast solution of ell_1 norm minimization
if nargin < 5, standardize = true; end
if nargin < 4, t = Inf; end
if nargin < 3, option = 'lar'; end
if strcmpi(option, 'lasso'), lasso = 1; else, lasso = 0; end
eps = 1e-10; % Effective zero
[n,p] = size(X);
if standardize,
X = normalize(X);
Y = Y-mean(Y);
end
m = min(p,n-1); % Maximal number of variables in the final active set
T = length(t);
beta = zeros(1,p);
mu = zeros(n,1); % Mean vector
gamma = []; % LARS step lengths
A = [];
Ac = 1:p;
nVars = 0;
signOK = 1;
i = 0;
mu_old = zeros(n,1);
t_prev = 0;
beta_t = zeros(T,p);
ii = 1;
tt = t;
% LARS loop
while nVars < m,
i = i+1;
c = X'*(Y-mu); % Current correlation
C = max(abs(c)); % Maximal current absolute correlation
if C < eps || isempty(t), break; end % Early stopping criteria
if 1 == i, addVar = find(C==abs(c)); end
if signOK,
A = [A,addVar]; % Add one variable to active set
nVars = nVars+1;
end
s_A = sign(c(A));
Ac = setdiff(1:p,A); % Inactive set
nZeros = length(Ac);
X_A = X(:,A);
G_A = X_A'*X_A; % Gram matrix
invG_A = inv(G_A);
L_A = 1/sqrt(s_A'*invG_A*s_A);
w_A = L_A*invG_A*s_A; % Coefficients of equiangular vector u_A
u_A = X_A*w_A; % Equiangular vector
a = X'*u_A; % Angles between x_j and u_A
beta_tmp = zeros(p,1);
gammaTest = zeros(nZeros,2);
if nVars == m,
gamma(i) = C/L_A; % Move to the least squares projection
else
for j = 1:nZeros,
jj = Ac(j);
gammaTest(j,:) = [(C-c(jj))/(L_A-a(jj)), (C+c(jj))/(L_A+a(jj))];
end
[gamma(i) min_i min_j] = minplus(gammaTest);
addVar = unique(Ac(min_i));
end
beta_tmp(A) = beta(i,A)' + gamma(i)*w_A; % Update coefficient estimates
% Check the sign feasibility of lasso
if lasso,
signOK = 1;
gammaTest = -beta(i,A)'./w_A;
[gamma2 min_i min_j] = minplus(gammaTest);
if gamma2 < gamma(i), % The case when sign consistency gets violated
gamma(i) = gamma2;
beta_tmp(A) = beta(i,A)' + gamma(i)*w_A; % Correct the coefficients
beta_tmp(A(unique(min_i))) = 0;
A(unique(min_i)) = []; % Delete the zero-crossing variable (keep the ordering)
nVars = nVars-1;
signOK = 0;
end
end
if Inf ~= t(1),
t_now = norm(beta_tmp(A),1);
if t_prev < t(1) && t_now >= t(1),
beta_t(ii,A) = beta(i,A) + L_A*(t(1)-t_prev)*w_A'; % Compute coefficient estimates corresponding to a specific t
t(1) = [];
ii = ii+1;
end
t_prev = t_now;
end
mu = mu_old + gamma(i)*u_A; % Update mean vector
mu_old = mu;
beta = [beta; beta_tmp'];
end
if 1 < ii,
noCons = (tt > norm(beta_tmp,1));
if 0 < sum(noCons),
beta_t(noCons,:) = repmat(beta_tmp',sum(noCons),1);
end
beta = beta_t;
end
% Normalize columns of X to have mean zero and length one.
function sX = normalize(X)
[n,p] = size(X);
sX = X-repmat(mean(X),n,1);
sX = sX*diag(1./sqrt(ones(1,n)*sX.^2));
% Find the minimum and its index over the (strictly) positive part of X
% matrix
function [m, I, J] = minplus(X)
% Remove complex elements and reset to Inf
[I,J] = find(0~=imag(X));
for i = 1:length(I),
X(I(i),J(i)) = Inf;
end
X(X<=0) = Inf;
m = min(min(X));
[I,J] = find(X==m);
You can have more information in the related paper:
Efron, Bradley; Hastie, Trevor; Johnstone, Iain; Tibshirani, Robert. Least angle regression. Ann. Statist. 32 (2004), no. 2, 407--499. doi:10.1214/009053604000000067.
http://projecteuclid.org/euclid.aos/1083178935.