The stairstep-look of the graph is unintentional. When I plot the same-sized vectors Arb and V (plot (Arb, V, 'r')) I get the following graph:
enter image description here
To make it smoother, I tried using 1-D data interpolation, interp1, as follows:
xq = 0:0.001:max(Arb);
Vq = interp1 (Arb, V, xq);
plot (xq, Vq);
However, I get this error message:
Error using interp1>reshapeAndSortXandV (line 416)
X must be a vector.
Error in interp1 (line 92)
[X,V,orig_size_v] = reshapeAndSortXandV(varargin{1},varargin{2})
interp1 will use linear interpolation on your data so it won't help you much. One thing you can try is to use a cubic spline with interp1 but again given the nature of the data I don't think it will help much. e.g.
Alternative 1. Cubic Spline
xq = 0:0.001:max(Arb);
Vq = interp1 (Arb, V, xq, 'spline');
plot (xq, Vq);
Alternative 2. Polynomial fit
Another alternative you can try is, polynomial interpolation using polyfit. e.g.
p = polifit(Arb, V, 2); % I think a 2nd order polynomial should do
xq = 0:0.001:max(Arb);
Vq = polyval(p, xq);
plot (xq, Vq);
Alternative 3. Alpha-beta filter
Last but not least, another thing to try is to use an smoothing alpha-beta filter on your V data. One possible implementation can be:
% x is the input data
% a is the "smoothing" factor from [0, 1]
% a = 0 full smoothing
% a = 1 no smoothing
function xflt = alphaBeta(x, a)
xflt = zeros(1,length(x));
xflt(1) = x(1);
a = max(min(a, 1), 0); % Bound coefficient between 0 and 1;
for n = 2:1:length(x);
xflt(n) = a * x(n) + (1 - a) * xflt(n-1);
end
end
Usage:
plot (Arb, alphaBeta(V, 0.65), 'r')
Related
I have this hard coded version which fits data to a curve for linear, quadratic and cubic polynomials:
for some data x and a function y
M=[x.^0 x.^1];
L=[x.^0 x.^1 x.^2];
linear = (M'*M)\(M'*y);
plot(x, linear(1)+linear(2)*x, ';linear;r');
deg2 = (L'*L)\(L'*y);
plot(x, deg2(1)+deg2(2)*x+deg2(3)*(x.*x), ';quadratic plot;b');
I am wondering how can I turn this into a for loop to plot curves for degree n polynomials? The part I'm stuck on is the plotting part, how would I be able to translate the increase in the number of coefficients in to the for loop?
what I have:
for i = 1:5 % say we're trying to plot curves up to degree 5 polynomials...
curr=x.^(0:i);
degI = (curr'*curr)\(curr'*y);
plot(x, ???) % what goes in here<-
end
If it is only the plotting, you can use the polyval function to evaluate polynomials of desired grade by supplying a vector of coefficients
% For example, some random coefficients for a 5th order polynomial
% degI = (curr'*curr)\(curr'*y) % Your case
degi = [3.2755 0.8131 0.5950 2.4918 4.7987 1.5464]; % for 5th order polynomial
x = linspace(-2, 2, 10000);
hold on
% Using polyval to loop over the grade of the polynomials
for i = 1:length(degI)
plot(x, polyval(degI(1:i), x))
end
gives the all polynomials in one plot
I believe this should answer your question exactly. You just have to be careful with the matrix dimensions.
for i = 1:5
curr=x.^(0:i);
degI = (curr'*curr)\(curr'*y);
plot(x, x.^(0:i)*degI)
end
Interpolate the Runge function of Example 10.6 at Chebyshev points for n from 10 to 170
in increments of 10. Calculate the maximum interpolation error on the uniform evaluation
mesh x = -1:.001:1 and plot the error vs. polynomial degree as in Figure 10.8 using
semilogy. Observe spectral accuracy.
The runge function is given by: f(x) = 1 / (1 + 25x^2)
My code so far:
x = -1:0.001:1;
n = 170;
i = 10:10:170;
cx = cos(((2*i + 1)/(2*(n+1)))*pi); %chebyshev pts
y = 1 ./ (1 + 25*x.^2); %true fct
%chebyshev polynomial, don't know how to construct using matlab
yc = polyval(c, x); %graph of approx polynomial fct
plot(x, yc);
mErr = (1 / ((2.^n).*(n+1)!))*%n+1 derivative of f evaluated at max x in [-1,1], not sure how to do this
%plotting stuff
I know very little matlab, so I am struggling on creating the interpolating polynomial. I did some google work, but I was confused with the current functions as I didn't find one that just simply took in points and the polynomial to be interpolated. I am also a bit confused in this case of whether I should be doing i = 0:1:n and n=10:10:170 or if n is fixed here. Any help is appreciated, thank you
Since you know very little about MATLAB, I will try explain everything step by step:
First, to visualize the Runge function, you can type:
f = #(x) 1./(1+25*x.^2); % Runge function
% plot Runge function over [-1,1];
x = -1:1e-3:1;
y = f(x);
figure;
plot(x,y); title('Runge function)'); xlabel('x');ylabel('y');
The #(x) part of the code is a function handle, a very useful feature of MATLAB. Notice the function is properly vecotrized, so it can receive as an argument a variable or an array. The plot function is straightforward.
To understand the Runge phenomenon, consider a linearly spaced vector of [-1,1] of 10 elements and use these points to obtain the interpolating (Lagrange) polynomial. You get the following:
% 10 linearly spaced points
xc = linspace(-1,1,10);
yc = f(xc);
p = polyfit(xc,yc,9); % gives the coefficients of the polynomial of degree 10
hold on; plot(xc,yc,'o',x,polyval(p,x));
The polyfit function does a polynomial curve fitting - it obtains the coefficients of the interpolating polynomial, given the poins x,y and the degree of the polynomial n. You can easily evaluate the polynomial at other points with the polyval function.
Obseve that, close to the end domains, you get an oscilatting polynomial and the interpolation is not a good approximation of the function. As a matter of fact, you can plot the absolute error, comparing the value of the function f(x) and the interpolating polynomial p(x):
plot(x,abs(y-polyval(p,x))); xlabel('x');ylabel('|f(x)-p(x)|');title('Error');
This error can be reduced if, instead of using a linearly space vector, you use other points to do the interpolation. A good choice is to use the Chebyshev nodes, which should reduce the error. As a matter of fact, notice that:
% find 10 Chebyshev nodes and mark them on the plot
n = 10;
k = 1:10; % iterator
xc = cos((2*k-1)/2/n*pi); % Chebyshev nodes
yc = f(xc); % function evaluated at Chebyshev nodes
hold on;
plot(xc,yc,'o')
% find polynomial to interpolate data using the Chebyshev nodes
p = polyfit(xc,yc,n-1); % gives the coefficients of the polynomial of degree 10
plot(x,polyval(p,x),'--'); % plot polynomial
legend('Runge function','Chebyshev nodes','interpolating polynomial','location','best')
Notice how the error is reduced close to the end domains. You don't get now that high oscillatory behaviour of the interpolating polynomial. If you plot the error, you will observe:
plot(x,abs(y-polyval(p,x))); xlabel('x');ylabel('|f(x)-p(x)|');title('Error');
If, now, you change the number of Chebyshev nodes, you will get an even better approximation. A little modification on the code lets you run it again for different numbers of nodes. You can store the maximum error and plot it as a function of the number of nodes:
n=1:20; % number of nodes
% pre-allocation for speed
e_ln = zeros(1,length(n)); % error for the linearly spaced interpolation
e_cn = zeros(1,length(n)); % error for the chebyshev nodes interpolation
for ii=1:length(n)
% linearly spaced vector
x_ln = linspace(-1,1,n(ii)); y_ln = f(x_ln);
p_ln = polyfit(x_ln,y_ln,n(ii)-1);
e_ln(ii) = max( abs( y-polyval(p_ln,x) ) );
% Chebyshev nodes
k = 1:n(ii); x_cn = cos((2*k-1)/2/n(ii)*pi); y_cn = f(x_cn);
p_cn = polyfit(x_cn,y_cn,n(ii)-1);
e_cn(ii) = max( abs( y-polyval(p_cn,x) ) );
end
figure
plot(n,e_ln,n,e_cn);
xlabel('no of points'); ylabel('maximum absolute error');
legend('linearly space','chebyshev nodes','location','best')
I want to fit a curve to some data. I used a PCHIP interpolation because of getting the best results. Moreover, I want to get the coefficients for the 6 intervals with the ppval-function. But there pops up an error like these:
Error using unmkpp (line 18)
The input array does not seem to describe a pp function.
Error in ppval (line 62)
[b,c,l,k,dd]=unmkpp(pp);
Error in SA (line 8)
v = ppval(p,xdata)
This is my code:
clear all
xdata = [0; 3.5; 6.8; 7.6; 8.2; 30; 34.2];
ydata = [0; 50; 400000; 2000000; 25000000; 100000000;100000000]
xq1 = 0:0.01:35;
p = pchip(xdata,ydata, xq1);
s = spline(xdata,ydata,xq1);
v = ppval(p,xdata)
plot(xdata,ydata,'o',xq1,p,'-',xq1,s,'-.');
legend('Datenpunkte','pchip','spline','Location','SouthEast');
Can you help me?
Best regards
Dominik
pchip has two working modes:
Calculating the piecewise polynomial coefficients: pp = pchip(x,y):
returns a piecewise polynomial structure for use with ppval
Interpolating at specified points: p = pchip(x,y,xq):
is the same as p = ppval(pchip(x,y),xq)
returns a vector of interpolated values p corresponding to the query
points in xq
So, you are using the second mode, which is not suited for use with ppval.
I have 2 vectors and a scalar:
grid which is (N x 1);
Value which is (N x 1);
sval which is (1,1);
If I want to interpolate sval on grid I know that I can simply do:
intervalue = interp1(grid, Value, sval, 'PCHIP');
What if now I want the derivatives, i.e. the slope of the function Value at that particular point sval?
As mentioned in the comments, you can approximate the derivative by forward finite difference approximation:
slope = diff(Value) ./ diff(grid);
Alternatively:
slope = gradient(Value(1:end-1),grid);
This is a simple method of numerical differentiation. For a detailed guide on numerical differentiation in MATALB, see this answer.
Here is an example of the finite difference method with the desired interpolation:
% Define function y = x^3
grid = 1:100;
Value = grid .^ 3;
% Approximate derivative via the local slope
slope = diff(Value) ./ diff(grid);
% Or: slope = gradient(Value(1:end-1),grid);
slope_grid = grid(1:end-1);
% Interpolate derivative
sval = 33.5;
sval_slope = interp1(slope_grid, slope, sval, 'PCHIP');
We can visualize the result:
figure;
plot(grid, 3*grid.^2)
hold on
plot(slope_grid, slope)
legend('Reference', 'Approximation', 'Location', 'NorthWest')
Given a system of the form y' = A*y(t) with solution y(t) = e^(tA)*y(0), where e^A is the matrix exponential (i.e. sum from n=0 to infinity of A^n/n!), how would I use matlab to compute the solution given the values of matrix A and the initial values for y?
That is, given A = [-2.1, 1.6; -3.1, 2.6], y(0) = [1;2], how would I solve for y(t) = [y1; y2] on t = [0:5] in matlab?
I try to use something like
t = 0:5
[y1; y2] = expm(A.*t).*[1;2]
and I'm finding errors in computing the multiplication due to dimensions not agreeing.
Please note that matrix exponential is defined for square matrices. Your attempt to multiply the attenuation coefs with the time vector doesn't give you what you'd want (which should be a 3D matrix that should be exponentiated slice by slice).
One of the simple ways would be this:
A = [-2.1, 1.6; -3.1, 2.6];
t = 0:5;
n = numel(t); %'number of samples'
y = NaN(2, n);
y(:,1) = [1;2];
for k =2:n
y(:,k) = expm(t(k)*A) * y(:,1);
end;
figure();
plot(t, y(1,:), t, y(2,:));
Please note that in MATLAB array are indexed from 1.