Matlab: Timestep stability in a 1D heat diffusion model - matlab

I have a 1D heat diffusion code in Matlab which I was using on a timescale of 10s of years and I am now trying to use the same code to work on a scale of millions of years. Obviously if I keep my timestep the same this will take ages to calculate but if I increase my timestep I encounter numerical stability issues.
My questions are:
How should I approach this problem? What affects the maximum stable timestep? And how do I calculate this?
Many thanks,
Alex
close all
clear all
dx = 4; % discretization step in m
dt = 0.0000001; % timestep in Myrs
h=1000; % height of box in m
nx=h/dx+1;
model_lenth=1; %length of model in Myrs
nt=ceil(model_lenth/dt)+1; % number of tsteps to reach end of model
kappa = 1e-6; % thermal diffusivity
x=0:dx:0+h; % finite difference mesh
T=38+0.05.*x; % initial T=Tm everywhere ...
time=zeros(1,nt);
t=0;
Tnew = zeros(1,nx);
%Lower sill
sill_1_thickness=18;
Sill_1_top_position=590;
Sill_1_top=ceil(Sill_1_top_position/dx);
Sill_1_bottom=ceil((Sill_1_top_position+sill_1_thickness)/dx);
%Upper sill
sill_2_thickness=10;
Sill_2_top_position=260;
Sill_2_top=ceil(Sill_2_top_position/dx);
Sill_2_bottom=ceil((Sill_2_top_position+sill_2_thickness)/dx);
%Temperature of dolerite intrusions
Tm=1300;
T(Sill_1_top:Sill_1_bottom)=Tm; %Apply temperature to intrusion 1
% unit conversion to SI:
secinmyr=24*3600*365*1000000; % dt in sec
dt=dt*secinmyr;
%Plot initial conditions
figure(1), clf
f1 = figure(1); %Make full screen
set(f1,'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
plot (T,x,'LineWidth',2)
xlabel('T [^oC]')
ylabel('x[m]')
axis([0 1310 0 1000])
title(' Initial Conditions')
set(gca,'YDir','reverse');
%Main calculation
for it=1:nt
%Apply temperature to upper intrusion
if it==10;
T(Sill_2_top:Sill_2_bottom)=Tm;
end
for i = 2:nx-1
Tnew(i) = T(i) + kappa*dt*(T(i+1) - 2*T(i) + T(i-1))/dx/dx;
end
Tnew(1) = T(1);
Tnew(nx) = T(nx);
time(it) = t;
T = Tnew; %Set old Temp to = new temp for next loop
tmyears=(t/secinmyr);
%Plot a figure which updates in the loop of temperature against depth
figure(2), clf
plot (T,x,'LineWidth',2)
xlabel('T [^oC]')
ylabel('x[m]')
title([' Temperature against Depth after ',num2str(tmyears),' Myrs'])
axis([0 1300 0 1000])
set(gca,'YDir','reverse');%Reverse y axis
%Make full screen
f2 = figure(2);
set(f2,'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
drawnow
t=t+dt;
end

The stability condition for an explicit scheme like FTCS is governed by $r = K dt/dx^2 < 1/2$ or $dt < dx^2/(2K)$ where K is your coefficient of diffusion. This is required in order to make the sign of the 4th order derivative leading truncation error term be negative.
If you do not want to be limited by timestep I suggest using an implicit scheme (albeit at a higher of computational cost than an explicit scheme). This can be achieved simply by using backward Euler for the diffusion term instead of forward Euler. Another option is Crank-Nicholson which is also implicit.

#Isopycnal Oscillation is totally correct in that the maximum stable step is limited in an explicit scheme. Just for reference this is usually referred to as the discrete Fourier number or just Fourier number and can be looked up for different boundary conditions.
also the following may help you for the derivation of the Implicit or Crank-Nicholson scheme and mentions stability Finite-Difference Approximations
to the Heat Equation by Gerald W. Recktenwald.
Sorry I don't have the rep yet to add comments

Related

MATLAB: How to apply ifft correctly to bring a "filtered" signal back to the time doamin?

I am trying to get the output of a Gaussian pulse going through a coax cable. I made a vector that represents a coax cable; I got attenuation and phase delay information online and used Euler's equation to create a complex array.
I FFTed my Gaussian vector and convoluted it with my cable. The issue is, I can't figure out how to properly iFFT the convolution. I read about iFFt in MathWorks and looked at other people's questions. Someone had a similar problem and in the answers, someone suggested to remove n = 2^nextpow2(L) and FFT over length(t) instead. I was able to get more reasonable plot from that and it made sense to why that is the case. I am confused about whether or not I should be using the symmetry option in iFFt. It is making a big difference in my plots. The main reason I added the symmetry it is because I was getting complex numbers in the iFFTed convolution (timeHF). I would truly appreciate some help, thanks!
clc, clear
Fs = 14E12; %1 sample per pico seconds
tlim = 4000E-12;
t = -tlim:1/Fs:tlim; %in pico seconds
ag = 0.5; %peak of guassian
bg = 0; %peak location
wg = 50E-12; %FWHM
x = ag.*exp(-4 .* log(2) .* (t-bg).^2 / (wg).^2); %Gauss. in terms of FWHM
Ly = x;
L = length(t);
%n = 2^nextpow2(L); %test output in time domain with and without as suggested online
fNum = fft(Ly,L);
frange = Fs/L*(0:(L/2)); %half of the spectrum
fNumMag = abs(fNum/L); %divide by n to normalize
% COAX modulation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%phase data
mu = 4*pi*1E-7;
sigma_a = 2.9*1E7;
sigma_b = 5.8*1E6;
a = 0.42E-3;
b = 1.75E-3;
er = 1.508;
vf = 0.66;
c = 3E8;
l = 1;
Lso = sqrt(mu) /(4*pi^3/2) * (1/(sqrt(sigma_a)*a) + 1/(b*sqrt(sigma_b)));
Lo = mu/(2*pi) * log(b/a);
%to = l/(vf*c);
to = 12E-9; %measured
phase = -pi*to*(frange + 1/2 * Lso/Lo * sqrt(frange));
%attenuation Data
k1 = 0.34190;
k2 = 0.00377;
len = 1;
mldb = (k1 .* sqrt(frange) + k2 .* frange) ./ 100 .* len ./1E6;
mldb1 = mldb ./ 0.3048; %original eqaution is in inch
tfMag = 10.^(mldb1./-10);
% combine to make in complex form
tfC = [];
for ii = 1: L/2 + 1
tfC(ii) = tfMag(ii) * (cosd(phase(ii)) + 1j*sind(phase(ii)));
end
%END ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%convolute both h and signal
fNum = fNum(1:L/2+1);
convHF = tfC.*fNum;
convHFMag = abs(convHF/L);
timeHF = ifft(convHF, length(t), 'symmetric'); %this is the part im confused about
% Ignore,
% tfC(numel(fNum)) = 0;
% convHF = tfC.*fNum;
% convHFMag = abs(convHF/n);
% timeHF = ifft(convHF);
%% plotting
% subplot(2, 2, 1);
% plot(t, Ly)
% title('Gaussian input');
% xlabel('time in seconds')
% ylabel('V')
% grid
subplot(2, 2, 1)
plot(frange, abs(tfC(1: L/2 + 1)));
set(gca, 'Xscale', 'log')
title('coax cable model')
xlabel('Hz')
ylabel('|H(s)|V/V')
grid
ylim([0 1.1])
subplot(2, 2, 2);
plot(frange, convHFMag(1:L/2+1), '.-', frange, fNumMag(1:L/2+1)) %make both range and function the same lenght
title('The input signal Vs its convolution with coax');
xlabel('Hz')
ylabel('V')
legend('Convolution','Lorentzian in frequecuency domain');
xlim([0, 5E10])
grid
subplot(2, 2, [3, 4]);
plot(t, Ly, t, timeHF)
% plot(t, real(timeHF(1:length(t)))) %make both range and function the same lenght
legend('Input', 'Output')
title('Signal at the output')
xlabel('time in seconds')
ylabel('V')
grid
It's important to understand deeply the principles of the FFT to use it correctly.
When you apply Fourier transform to a real signal, the coefficients at negative frequencies are the conjugate of the ones at positive frequencies. When you apply FFT to a real numerical signal, you can show mathematically that the conjugates of the coefficients that should be at negative frequencies (-f) will now appear at (Fsampling-f) where Fsampling=1/dt is the sampling frequency and dt the sampling period. This behavior is called aliasing and is present when you apply fft to a discrete time signal and the sampling period should be chosen small enaough for those two spectra not to overlap Shannon criteria.
When you want to apply a frequency filter to a signal, we say that we keep the first half of the spectrum because the high frequencies (>Fsampling/2) are due to aliasing and are not characteristics of the original signal. To do so, we put zeros on the second half of the spectra before multiplying by the filter. However, by doing so you also lose half of the amplitude of the original signal that you will not recover with ifft. The option 'symmetric' enable to recover it by adding in high frequencis (>Fsampling/2) the conjugate of the coefficients at lower ones (<Fsampling/2).
I simplified the code to explain briefly what's happening and implemented for you at line 20 a hand-made symmetrisation. Note that I reduced the sampling period from one to 100 picoseconds for the spectrum to display correctly:
close all
clc, clear
Fs = 14E10; %1 sample per pico seconds % CHANGED to 100ps
tlim = 4000E-12;
t = -tlim:1/Fs:tlim; %in pico seconds
ag = 0.5; %peak of guassian
bg = 0; %peak location
wg = 50E-12; %FWHM
NT = length(t);
x_i = ag.*exp(-4 .* log(2) .* (t-bg).^2 / (wg).^2); %Gauss. in terms of FWHM
fftx_i = fft(x_i);
f = 1/(2*tlim)*(0:NT-1);
fftx_r = fftx_i;
fftx_r(floor(NT/2):end) = 0; % The removal of high frequencies due to aliasing leads to losing half the amplitude
% HER YOU APPLY FILTER
x_r1 = ifft(fftx_r); % without symmetrisation (half the amplitude lost)
x_r2 = ifft(fftx_r, 'symmetric'); % with symmetrisation
x_r3 = ifft(fftx_r+[0, conj(fftx_r(end:-1:2))]); % hand-made symmetrisation
figure();
subplot(211)
hold on
plot(t, x_i, 'r')
plot(t, x_r2, 'r-+')
plot(t, x_r3, 'r-o')
plot(t, x_r1, 'k--')
hold off
legend('Initial', 'Matlab sym', 'Hand made sym', 'No sym')
title('Time signals')
xlabel('time in seconds')
ylabel('V')
grid
subplot(212)
hold on
plot(f, abs(fft(x_i)), 'r')
plot(f, abs(fft(x_r2)), 'r-+')
plot(f, abs(fft(x_r3)), 'r-o')
plot(f, abs(fft(x_r1)), 'k--')
hold off
legend('Initial', 'Matlab sym', 'Hand made sym', 'No sym')
title('Power spectra')
xlabel('frequency in hertz')
ylabel('V')
grid
Plots the result:
Do not hesitate if you have further questions. Good luck!
---------- EDIT ----------
The amplitude of discrete Fourier transform is not the same as the continuous one. If you are interested in showing signal in frequency domain, you will need to apply a normalization based on the convention you have chosen. In general, you use the convention that the amplitude of the Fourier transform of a Dirac delta function has amplitude one everywhere.
A numerical Dirac delta function has an amplitude of one at an index and zeros elsewhere and leads to a power spectrum equal to one everywhere. However in your case, the time axis has sample period dt, the integral over time of a numerical Dirac in that case is not 1 but dt. You must normalize your frequency domain signal by multiplying it by a factor dt (=1picoseceond in your case) to respect the convention. You can also note that this makes the frequency domain signal homogeneous to [unit of the original multiplied by a time] which is the correct unit of a Fourier transform.

Heat Flow Equation Matlab

I'm currently working on a project to build a solar food dryer and I need to model on Matlab how temperature of the product will change with respect to change in solar radiation, Q .
Q is given by ;
Q =960*(sin(2*pi*Time2/24)).^2; %W/m2
where
Time2 = (1:t:12); %hours
The heat flow equation is given by
Q(t)A = mcp*(T2-T1) + (mw*lw)
where :
mw = 0.706; % Mass of water loss from product in hr (Kg/h)
m = 15; % Mass of product to dry (Kg)
lw = 2260000; % Latent heat of vaporisation of water (J/Kg)
A = 1; % Surface Area of collector (m^2)
cp= 3746; % Specific heat capacity of product (J/Kg/C)
T1 = temperature at t
T2 = temperature at t + dt
Manipulating the heat flow give T2 as ;
T2= (((Q*A*3600) -(mw*lw))/(m*cp)) + T1; % 3600 is there to convert j/s to J/h
however implementing this on Matlab is proving a challenge for me- I'm fairly new to Matlab
This is what I have so far ;
close all
clear;
mw = 0.706; % Mass of water loss from product in hr (Kg/h)
m = 15; % Mass of product to dry (Kg)
lw = 2260000; % Latent heat of vaporisation of water (J/Kg)
A = 1; % Surface Area of Collector (m^2)
cp= 3746; % Specific heat capacity of product (J/Kg/C)
t = 1; % Time step
T = 24; % Initial Temperature (°C)
Time2=(1:t:12); hours
Q=960*(sin(2*pi*Time2/24)).^2; % Solar irradiation in tropical regions at specific time (W/m2)
for j = 1:12
T(j+1)= ((((QQ2(j)*A*j*3600))-(mw*lw))/(m*cp))+ T(1);
end
figure(2)
plot(T)
title('Temperature')
xlabel('time (hours)')
ylabel('Temperature (°C)')
This seems wrong since the mass, m should decrease by mw after each hr and the temperature profile should follow the profile of the solar radiation. i.e peak at the same time
I have been spending days to get my head around this but i'm pretty bad at Matlab so I haven't made any meaningful progress. Any help will be appreciated
So I am not sure if this is what you are looking for Ran, but there are a few points that looked like typos (?) and these would change behaviour. You have QQ2(j) suddenly appears in the middle of your script... I presumed that was just Q[j). Each cycle of your loop you add to t(1) and I think you meant t(j)? And surely the loop should also decrease the m?
So I modified to this...
for j = 1:12
T(j+1)= ((((Q(j)*A*j*3600))-(mw*lw))/(m*cp))+ T(j);
m=m-mw*t;
end
Now T peaks at 12noon.
All that said, I would think a problem like this would be better solved with a differential equation solver like ‘ode45()’, but I would need to see that differential equation before advising how to do that in Matlab, but it shouldn’t be too tricky!
### Hello again Ran, OK you have added the dydx in the the comments now so here is how I would approach this problem, (accepting I don’t know much about this equation itself!):
clear;
global conv;
conv=60*60;
mw = 0.706/conv; % Mass of water loss from product in hr (Kg/h)
m = 15.0; % Mass of product to dry (Kg)
lw = 2260000.0; % Latent heat of vaporisation of water (J/Kg)
A= 1.0; % Surface Area of Collector (m^2)
cp= 3746.0; % Specific heat capacity of product (J/Kg/C)
T = 24.0; % Initial Temperature (°C)
%%
%% for j = 1:12
%% T(j+1)= ((((Q(j)*A*j*3600))-(mw*lw))/(m*cp))+ T(j);
%% m=m-mw*t;
%% end
tspan = [0, 12*conv];
yo=[T;m];
[t,y] = ode45(#(t,y) ode(t, y,[A,mw,lw,cp]), tspan, yo);
yfinal=y;
figure (1)
plot(t./conv,yfinal(:,1))
title('Temperature')
xlabel('time (hours)')
ylabel('Temperature (°C)')
figure (2)
tqs=linspace(0,12);
Qt=960.0*(sin(2.0.*pi.*tqs./(24.0))).^2;
plot(tqs,Qt);
function dydt=ode(t,y,x)
global conv;
A =x(1);
mw =x(2);
lw =x(3);
cp =x(4);
m=y(2);
Q=960*(sin(2*pi*t/(24*conv)))^2; % Solar irradiation in tropical regions at specific time (W/m2)
dydt=[((Q * A)-(mw*lw))/(m*cp);-mw];
end
This gives this output, I think the equations will need a fiddle, but hopefully the structure of the ODE helps?
P.s., I am not convinced that peak temperature would match peak heat input since usually there is a lag. Hottest part of the day is often 3pm in the UK... but I haven’t looked at heat transfer since High School...
Regards R

Extract the values for some parameters from stochastic differential equation solution

I am solving stochastic differential equation in matlab.
For example:
consider the stochastic differential equation
dx=k A(x,t)dt+ B(x,t)dW(t)
where k is constants, A and B are functions, and dW(t) is Wiener process.
I plot the solution for all t in [0,20]. We know that dW(t) is randomly generated. My question is: I want to know the value of A(x,t), B(x,t), dW(t) for a particular value of t and for particular sub-interval, say [3,6]. What command in Matlab I can use?
Here is the code I used based on a paper by D.Higham:
clear all
close all
t0 = 0; % start time of simulation
tend = 20; % end time
m=2^9; %number of steps in each Brownian path
deltat= tend/m; % time increment for each Brownian path
D=0.1; %diffsuion
R=4;
dt = R*deltat;
dW=sqrt( deltat)*randn(2,m);
theta0=pi*rand(1);
phi0=2*pi*rand(1);
P_initial=[ theta0; phi0];
L = m/ R;
pem=zeros(2,L);
EM_rescale=zeros(2,L);
ptemp=P_initial;
for j=1:L
Winc = sum(dW(:,[ R*(j-1)+1: R*j]),2);
theta=ptemp(1);% updating theta
phi=ptemp(2); % updating phi
%psi=ptemp(3); % updating psi
A=[ D.*cot(theta);...
0];% updating the drift
B=[sqrt(D) 0 ;...
0 sqrt(D)./sin(theta) ]; %% updating the diffusion function
ptemp=ptemp+ dt*A+B*Winc;
pem(1,j)=ptemp(1);%store theta
pem(2,j)=ptemp(2);%store phi
EM_rescale(1,j)=mod(pem(1,j),pi); % re-scale theta
EM_rescale(2,j)=mod(pem(2,j),2*pi); % re-scale phi
end
plot([0:dt:tend],[P_initial,EM_rescale],'--*')
Suppose I want to know all parameters (including random: Brownian) at each specific time point or for any time interval. How to do that?
I'm doing my best to understand your question here, but it's still a bit unclear to me.
Change the loop to:
for ii=1:L
Winc = sum(dW(:,[ R*(ii-1)+1: R*ii]),2);
theta=ptemp(1);% updating theta
phi=ptemp(2); % updating phi
A{ii}=[ D.*cot(theta);...
0];% updating the drift
B{ii}=[sqrt(D) 0 ;...
0 sqrt(D)./sin(theta) ]; %% updating the diffusion function
ptemp = ptemp + dt*A{ii}+B{ii}*Winc;
pem(:,ii) = ptemp;
EM_rescale(1,ii) = mod(pem(1,ii),pi); % re-scale theta
EM_rescale(2,ii) = mod(pem(2,ii),2*pi); % re-scale phi
end
Now, you can get the values of A and B this way:
t = 3;
t_num = round(m/tend*t);
A{t_num}
B{t_num}
ans =
0.0690031455719538
0
ans =
0.316227766016838 0
0 0.38420611784333

Finding the best monotonic curve fit

Edit: Some time after I asked this question, an R package called MonoPoly (available here) came out that does exactly what I want. I highly recommend it.
I have a set of points I want to fit a curve to. The curve must be monotonic (never decreasing in value) i.e. the curve can only go upward or stay flat.
I originally had been polyfitting my results and this had been working great until I found a particular dataset. The polyfit for data in this dataset was non-monotonic.
I did some research and found a possible solution in this post:
Use lsqlin. Constrain the first derivative to be non-negative at both
ends of the domain of interest.
I'm coming from a programming rather than math background so this is a little beyond me. I don't know how to constrain the first derivative to be non-negative as he said. Also, I think in my case I need a curve so I should use lsqcurvefit but I don't know how to constrain it to produce monotonic curves.
Further research turned up this post recommending lsqcurvefit but I can't figure out how to use the important part:
Try this non-linear function F(x) also. You use it together with
lsqcurvefit but it require a start guess on the parameters. But it is
a nice analytic expression to give as a semi-empirical formula in a
paper or a report.
%Monotone function F(x), with c0,c1,c2,c3 varitional constants F(x)=
c3 + exp(c0 - c1^2/(4*c2))sqrt(pi)...
Erfi((c1 + 2*c2*x)/(2*sqrt(c2))))/(2*sqrt(c2))
%Erfi(x)=erf(i*x) (look mathematica) but the function %looks much like
x^3 %derivative f(x), probability density f(x)>=0
f(x)=dF/dx=exp(c0+c1*x+c2*x.^2)
I must have a monotonic curve but I'm not sure how to do it, even with all of this information. Would a random number be enough for a "start guess". Is lsqcurvefit best? How can I use it to produce a best fitting monotonic curve?
Thanks
Here is a simple solution using lsqlin. The derivative constrain is enforced in each data point, this could be easily modified if needed.
Two coefficient matrices are needed, one (C) for least square error calculation and one (A) for derivatives in the data points.
% Following lsqlin's notations
%--------------------------------------------------------------------------
% PRE-PROCESSING
%--------------------------------------------------------------------------
% for reproducibility
rng(125)
degree = 3;
n_data = 10;
% dummy data
x = rand(n_data,1);
d = rand(n_data,1) + linspace(0,1,n_data).';
% limit on derivative - in each data point
b = zeros(n_data,1);
% coefficient matrix
C = nan(n_data, degree+1);
% derivative coefficient matrix
A = nan(n_data, degree);
% loop over polynomial terms
for ii = 1:degree+1
C(:,ii) = x.^(ii-1);
A(:,ii) = (ii-1)*x.^(ii-2);
end
%--------------------------------------------------------------------------
% FIT - LSQ
%--------------------------------------------------------------------------
% Unconstrained
% p1 = pinv(C)*y
p1 = fliplr((C\d).')
p2 = polyfit(x,d,degree)
% Constrained
p3 = fliplr(lsqlin(C,d,-A,b).')
%--------------------------------------------------------------------------
% PLOT
%--------------------------------------------------------------------------
xx = linspace(0,1,100);
plot(x, d, 'x')
hold on
plot(xx, polyval(p1, xx))
plot(xx, polyval(p2, xx),'--')
plot(xx, polyval(p3, xx))
legend('data', 'lsq-pseudo-inv', 'lsq-polyfit', 'lsq-constrained', 'Location', 'southoutside')
xlabel('X')
ylabel('Y')
For the specified input the fitted curves:
Actually this code is more general than what you requested, since the degree of polynomial can be changed as well.
EDIT: enforce derivative constrain in additional points
The issue pointed out in the comments is due to that the derivative checks are enforced only in the data points. Between those no checks are performed. Below is a solution to alleviate this problem. The idea: convert the problem to an unconstrained optimization by using a penalty term.
Note that it is using a term pen to penalize the violation of the derivative check, thus the result is not a true least square error solution. Additionally, the result is dependent on the penalty function.
function lsqfit_constr
% Following lsqlin's notations
%--------------------------------------------------------------------------
% PRE-PROCESSING
%--------------------------------------------------------------------------
% for reproducibility
rng(125)
degree = 3;
% data from comment
x = [0.2096 -3.5761 -0.6252 -3.7951 -3.3525 -3.7001 -3.7086 -3.5907].';
d = [95.7750 94.9917 90.8417 62.6917 95.4250 89.2417 89.4333 82.0250].';
n_data = length(d);
% number of equally spaced points to enforce the derivative
n_deriv = 20;
xd = linspace(min(x), max(x), n_deriv);
% limit on derivative - in each data point
b = zeros(n_deriv,1);
% coefficient matrix
C = nan(n_data, degree+1);
% derivative coefficient matrix
A = nan(n_deriv, degree);
% loop over polynom terms
for ii = 1:degree+1
C(:,ii) = x.^(ii-1);
A(:,ii) = (ii-1)*xd.^(ii-2);
end
%--------------------------------------------------------------------------
% FIT - LSQ
%--------------------------------------------------------------------------
% Unconstrained
% p1 = pinv(C)*y
p1 = (C\d);
lsqe = sum((C*p1 - d).^2);
p2 = polyfit(x,d,degree);
% Constrained
[p3, fval] = fminunc(#error_fun, p1);
% correct format for polyval
p1 = fliplr(p1.')
p2
p3 = fliplr(p3.')
fval
%--------------------------------------------------------------------------
% PLOT
%--------------------------------------------------------------------------
xx = linspace(-4,1,100);
plot(x, d, 'x')
hold on
plot(xx, polyval(p1, xx))
plot(xx, polyval(p2, xx),'--')
plot(xx, polyval(p3, xx))
% legend('data', 'lsq-pseudo-inv', 'lsq-polyfit', 'lsq-constrained', 'Location', 'southoutside')
xlabel('X')
ylabel('Y')
%--------------------------------------------------------------------------
% NESTED FUNCTION
%--------------------------------------------------------------------------
function e = error_fun(p)
% squared error
sqe = sum((C*p - d).^2);
der = A*p;
% penalty term - it is crucial to fine tune it
pen = -sum(der(der<0))*10*lsqe;
e = sqe + pen;
end
end
Gradient free methods might be used to solve the problem by exactly enforcing the derivative constrain, for example:
[p3, fval] = fminsearch(#error_fun, p_ini);
%--------------------------------------------------------------------------
% NESTED FUNCTION
%--------------------------------------------------------------------------
function e = error_fun(p)
% squared error
sqe = sum((C*p - d).^2);
der = A*p;
if any(der<0)
pen = Inf;
else
pen = 0;
end
e = sqe + pen;
end
fmincon with non-linear constraint might be a better choice.
I let you to work out the details and to tune the algorithms. I hope that it is sufficient.

on the use and understanding of pwelch in matlab

I'm using the pwelch method in matlab to compute the power spectra for some wind speed measurements. So, far I have written the following code as an example:
t = 10800; % number of seconds in 3 hours
t = 1:t; % generate time vector
fs = 1; % sampling frequency (seconds)
A = 2; % amplitude
P = 1000; % period (seconds), the time it takes for the signal to repeat itself
f1 = 1/P; % number of cycles per second (i.e. how often the signal repeats itself every second).
y = A*sin(2*pi*f1*t); % signal
fh = figure(1);
set(fh,'color','white','Units', 'Inches', 'Position', [0,0,6,6],...
'PaperUnits', 'Inches', 'PaperSize', [6,6]);
[pxx, f] = pwelch(y,[],[],[],fs);
loglog(f,10*(pxx),'k','linewidth',1.2);
xlabel('log10(cycles per s)');
ylabel('Spectral Density (dB Hz^{-1})');
I cannot include the plot as I do not have enough reputation points
Does this make sense? I'm struggling with the idea of having noise at the right side of the plot. The signal which was decomposed was a sine wave with no noise, where does this noise come from? Does the fact that the values on the yaxis are negative suggest that those frequencies are negligible? Also, what would be the best way to write the units on the y axis if the wind speed is measured in m/s, can this be converted to something more meaningful for environmental scientists?
Your results are fine. dB can be confusing.
A linear plot will get a good view,
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sample time
L = 1000; % Length of signal
t = (0:L-1)*T; % Time vector
y = sin(2 * pi * 50 * t); % 50Hz signal
An fft approach,
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
Y = fft(y,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
subplot(1,2,1);
plot(f,2*abs(Y(1:NFFT/2+1)))
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')
pwelch approach,
subplot(1,2,2);
[pxx, freq] = pwelch(y,[],[],[],Fs);
plot(freq,10*(pxx),'k','linewidth',1.2);
xlabel('Frequency (Hz)');
ylabel('Spectral Density (Hz^{-1})');
As you can see they both have peak at 50Hz.
Using loglog for both,
So "noise" is of 1e-6 and exists in fft as well, and can be ignored.
For your second question, I don't think the axis will change it will be frequency again. For Fs you should use the sampling frequency of wind speed, like if you have 10 samples of speed in one second your Fs is 10. Higher frequencies in your graph means more changes in wind speed and lower frequencies represent less changes for the speed.