I'm trying to fit a shape perserving interpolation curve to my angular data (r/phi).
However, as I have repeated x-values when I transform the datapoints to (x/y), I can not simply use pchip.
I know for spline interpolation, there is cscvn and fnplt, is there anything similar for pchip?
Furthermore, there is an example of spline fitting to angular data in the matlab documentation of "spline", but I don't quite get it how I could adapt it to pchip and different data points.
I also found the interparc-function by John d'Errico, but I would like to keep my datapoints instead of having equally spaced ones.
To make it clearer, here a figure of my datapoints with linear (blue) and spline interpolation (black). The curve I'd like to get would be something in between this two, without the steep edges in the linear case but with less overshoot than in the spline case....
Thanks for your help!
use 1D parametric interpolation:
n = 20;
r = 1 + rand(n-1,1)*0.01;%noisy r's
theta = sort(2*pi*rand(n-1,1));
% closing the circle
r(end+1) = r(1);
theta(end+1) = theta(1);
% convert to cartesian
[x,y] = pol2cart(theta,r);
% interpolate with parameter t
t = (1:n)';
v = [x,y];
tt = linspace(1,n,100);
X = interp1(t,v,tt,'pchip');
% plot
plot(x,y,'o');
hold on
plot(X(:,1),X(:,2));
Related
I am using MATLAB to try to interpolate data for an object that is moving in 3D space at variable speed. I am starting with an array with columns: time, x, y, z, velocity. I want to interpolate the xyz path, but I can't figure out how to interpolate time and velocity at the same points that the xyz interpolation produces.
My problem is that if I interpolate using the cscvn function and fnval, then the interpolated points are not evenly spaced (yellow stars in the below image) and I'm not sure how to interpolate the times and speeds for those points.
Alternatively if I interpolate with interp1, it does produce evenly spaced points, but the interpolation is not better with cscvn.
I tried doing a 5 dimensional interpolation, and that didn't produce the desired results. I'm not sure how to deal with this problem.
How can I interpolate the xyz path, and then interpolate the time and velocities at those unevenly spaced points?
Here is the code I am using:
% Generate some fake data
flightPathRate = 1;
x = (-5:flightPathRate:10)';
y = sin(4*x);
z = linspace(3,5, length(x))';
t = ((0:length(x)-1)*flightPathRate)';
vel = x.^2 + 10;
pathData = [t x y z vel];
% Interpolate with cscvn
curve = cscvn(pathData(:,2:4)');
plot3(x, y, z, 'ob-')
hold on
fnplt(curve)
% Evaluate the spline curve created with cscvn at finer points.
splinePoints = fnval(curve, 0:0.1:16);
plot3(splinePoints(1,:), splinePoints(2,:), splinePoints(3,:), '*')
%% Interpolate with interp1
cs = cat(1,0,cumsum(sqrt(sum(diff([x, y, z], [], 1).^2, 2))));
dd = interp1(cs, [x, y, z], unique([cs(:)' linspace(0,cs(end),100)]), 'spline')
hold on
plot3(dd(:,1), dd(:,2), dd(:,3), '.r-')
axis image, view(3), legend({'Original', 'Spline Curve with cscvn/fnplt', 'Interp. Points with cscvn/fnval', 'Interp. Spline with interp1'})
Here is the plot produced.
I ran your code successfully.
Q.1: Please explain the role of velocity in your code. You define vel as fake data, at every fake data time point. But it is totally unrelated to the x,y,z fake data.
Answer to your question about how to determine the times associated with the x,y,z points which you get from cscvn(): there is no reasonable proven way to do that. Therefore I recommend that you not use cscvn(). Its main advantage is to make periodic splines, i.e. splines for cirves that return to their origin. But this problem is not like that.
Your interpolated data from interp1() looks good to me. I would go with it. It is a simple matter to esitmate velocity (|v| and vx, vy, vz) from the interpolated points. When you do, I recommend using the interpolated points before and after each point, to get an un-shifted estimate in the middle. Try the 'makima' or 'pchip' method with interp1(), instead of the 'spline' method, if you think 'spline' overshoots too much.
Say I've got a number of curves with different length (number of points in each curve and points distance are all vary). Could I find a curve in 3D space that fit best for this group of lines?
Code example in Matlab would be appreciated.
example data set:
the 1st curve has 10 points.
18.5860 18.4683 18.3576 18.2491 18.0844 17.9016 17.7709 17.6401 17.4617 17.2726
91.6178 91.5711 91.5580 91.5580 91.5701 91.6130 91.5746 91.5050 91.3993 91.2977
90.6253 91.1090 91.5964 92.0845 92.5565 93.0199 93.5010 93.9785 94.4335 94.8851
the 2nd curve has 8 points.
15.2091 15.0894 14.9765 14.8567 14.7360 14.6144 14.4695 14.3017
90.1138 89.9824 89.8683 89.7716 89.6889 89.6040 89.4928 89.3624
99.4393 99.9066 100.3802 100.8559 101.3340 101.8115 102.2770 102.7296
a desired curve is one that could represent these two exist curves.
I have thinking of make these curves as points scatters and fit a line out of them. But only a straight line can I get from many code snippet online.
So did I missing something or could someone provide some hint. Thanks.
Hard to come up with a bulletproof solution without more details, but here's an approach that works for the sample data provided. I found the line of best fit for all the points, and then parameterized all the points along that line of best fit. Then I did least-squares polynomial fitting for each dimension separately. This produced a three-dimensional parametric curve that seems to fit the data just fine.
Note that curve fitting approaches other than polynomial least-squares might be better suited to some cases---just substitute the preferred fitting function for polyfit and polyval.
Hope this is helpful!
clear;
close all;
pts1=[18.5860 18.4683 18.3576 18.2491 18.0844 17.9016 17.7709 17.6401 17.4617 17.2726;
91.6178 91.5711 91.5580 91.5580 91.5701 91.6130 91.5746 91.5050 91.3993 91.2977;
90.6253 91.1090 91.5964 92.0845 92.5565 93.0199 93.5010 93.9785 94.4335 94.8851]';
pts2=[ 15.2091 15.0894 14.9765 14.8567 14.7360 14.6144 14.4695 14.3017;
90.1138 89.9824 89.8683 89.7716 89.6889 89.6040 89.4928 89.3624;
99.4393 99.9066 100.3802 100.8559 101.3340 101.8115 102.2770 102.7296]';
%Combine all of our curves into a single point cloud
X = [pts1;pts2];
%=======================================================
%We want to first find the line of best fit
%This line will provide a parameterization of the points
%See accepted answer to http://stackoverflow.com/questions/10878167/plot-3d-line-matlab
% calculate centroid
x0 = mean(X)';
% form matrix A of translated points
A = [(X(:, 1) - x0(1)) (X(:, 2) - x0(2)) (X(:, 3) - x0(3))];
% calculate the SVD of A
[~, S, V] = svd(A, 0);
% find the largest singular value in S and extract from V the
% corresponding right singular vector
[s, i] = max(diag(S));
a = V(:, i);
%=======================================================
a=a / norm(a);
%OK now 'a' is a unit vector pointing along the line of best fit.
%Now we need to compute a new variable, 't', for each point in the cloud
%This 't' value will parameterize the curve of best fit.
%Essentially what we're doing here is taking the dot product of each
%shifted point (contained in A) with the normal vector 'a'
t = A * a;
tMin = min(t);
tMax = max(t);
%This variable represents the order of our polynomial fit
%Use the smallest number that produces a satisfactory result
polyOrder = 8;
%Polynomial fit all three dimensions separately against t
pX = polyfit(t,X(:,1),polyOrder);
pY = polyfit(t,X(:,2),polyOrder);
pZ = polyfit(t,X(:,3),polyOrder);
%And that's our curve fit: (pX(t),pY(t),pZ(t))
%Now let's plot it.
tFine = tMin:.01:tMax;
fitXFine = polyval(pX,tFine);
fitYFine = polyval(pY,tFine);
fitZFine = polyval(pZ,tFine);
figure;
scatter3(X(:,1),X(:,2),X(:,3));
hold on;
plot3(fitXFine,fitYFine,fitZFine);
hold off;
It seems to be very basic question, but I wonder when I plot x values against y values, what interpolation technique is used behind the scene to show me the discrete data as continuous? Consider the following example:
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
My guess is it is a Lagrangian interpolation?
No, it's just a linear interpolation. Your example uses a quite long dataset, so you can't tell the difference. Try plotting a short dataset and you'll see it.
MATLAB's plot performs simple linear interpolation. For finer resolution you'd have to supply more sample points or interpolate between the given x values.
For example taking the sinus from the answer of FamousBlueRaincoat, one can just create an x vector with more equidistant values. Note, that the linear interpolated values coincide with the original plot lines, as the original does use linear interpolation as well. Note also, that the x_ip vector does not include (all) of the original points. This is why the do not coincide at point (~0.8, ~0.7).
Code
x = 0:pi/4:2*pi;
y = sin(x);
x_ip = linspace(x(1),x(end),5*numel(x));
y_lin = interp1(x,y,x_ip,'linear');
y_pch = interp1(x,y,x_ip,'pchip');
y_v5c = interp1(x,y,x_ip,'v5cubic');
y_spl = interp1(x,y,x_ip,'spline');
plot(x,y,x_ip,y_lin,x_ip,y_pch,x_ip,y_v5c,x_ip,y_spl,'LineWidth',1.2)
set(gca,'xlim',[pi/5 pi/2],'ylim',[0.5 1],'FontSize',16)
hLeg = legend(...
'No Interpolation','Linear Interpolation',...
'PChip Interpolation','v5cubic Interpolation',...
'Spline Interpolation');
set(hLeg,'Location','south','Fontsize',16);
By the way..this does also apply to mesh and others
[X,Y] = meshgrid(-8:2:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
figure
mesh(Z)
No, Lagrangian interpolation with 200 equally spaced points would be an incredibly bad idea. (See: Runge's phenomenon).
The plot command simply connects the given (x,y) points by straight lines, in the order given. To see this for yourself, use fewer points:
x = 0:pi/4:2*pi;
y = sin(x);
plot(x,y)
In the theory of tomography imaging a sinogram is recorderded, which is series of projections at different angles of the sample. Taking FFT of this projections gives a slice in polar coordinates of the sample in the frequency space.
The command [X,Y] = pol2cart(THETA,RHO) will not do it automatically. So, how is the polar to cartesian grid interpolation implemented numerically in 2D in Matlab?
You need to do a phase transformation:
theta = 0:0.1:2*pi;
rho = linspace(0,1,numel(theta));
[x,y] = pol2cart(-theta+pi/2,rho);
figure;
subplot(1,2,1);
polar(theta,rho);
subplot(1,2,2);
plot(y,x);
axis([-1 1 -1 1]);
grid on;
The function [X,Y] = pol2cart(THETA,RHO) only performs the coordinate value conversion, i.e., X = RHO * cos(THETA) and Y = RHO * sin(THETA). However, what you need is the conversion of the data array, thus pol2cart() can do nothing to your problem.
You can refer to the function interp2(). On the other hand, since this problem is the interpolation with COMPLEX data, I am NOT sure whether interp2() could do the job directly. I also need the theory for complex interpolation.
I'm currently frustrated by the following problem:
I've got trajectory data (i.e.: Longitude and Latitude data) which I interpolate to find a linear fitting (using polyfit and polyval in matlab).
What I'd like to do is to rotate the axes in a way that the x-axis (the Longitude one) ends up lying on the best-fit line, and therefore my data should now lie on this (rotated) axis.
What I've tried is to evaluate the rotation matrix from the slope of the line-of-fit (m in the formula for a first grade polynomial y=mx+q) as
[cos(m) -sin(m);sin(m) cos(m)]
and then multiply my original data by this matrix...to no avail!
I keep obtaining a plot where my data lay in the middle and not on the x-axis where I expect them to be.
What am I missing?
Thank you for any help!
Best Regards,
Wintermute
A couple of things:
If you have a linear function y=mx+b, the angle of that line is atan(m), not m. These are approximately the same for small m', but very different for largem`.
The linear component of a 2+ order polyfit is different than the linear component of a 1st order polyfit. You'll need to fit the data twice, once at your working level, and once with a first order fit.
Given a slope m, there are better ways of computing the rotation matrix than using trig functions (e.g. cos(atan(m))). I always try to avoid trig functions when performing geometry and replace them with linear algebra operations. This is usually faster, and leads to fewer problems with singularities. See code below.
This method is going to lead to problems for some trajectories. For example, consider a north/south trajectory. But that is a longer discussion.
Using the method described, plus the notes above, here is some sample code which implements this:
%Setup some sample data
long = linspace(1.12020, 1.2023, 1000);
lat = sin ( (long-min(long)) / (max(long)-min(long))*2*pi )*0.0001 + linspace(.2, .31, 1000);
%Perform polynomial fit
p = polyfit(long, lat, 4);
%Perform linear fit to identify rotation
pLinear = polyfit(long, lat, 1);
m = pLinear(1); %Assign a common variable for slope
angle = atan(m);
%Setup and apply rotation
% Compute rotation metrix using trig functions
rotationMatrix = [cos(angle) sin(angle); -sin(angle) cos(angle)];
% Compute same rotation metrix without trig
a = sqrt(m^2/(1+m^2)); %a, b are the solution to the system:
b = sqrt(1/(1+m^2)); % {a^2+b^2 = 1}, {m=a/b}
% %That is, the point (b,a) is on the unit
% circle, on a line with slope m
rotationMatrix = [b a; -a b]; %This matrix rotates the point (b,a) to (1,0)
% Generally you rotate data after removing the mean value
longLatRotated = rotationMatrix * [long(:)-mean(long) lat(:)-mean(lat)]';
%Plot to confirm
figure(2937623)
clf
subplot(211)
hold on
plot(long, lat, '.')
plot(long, polyval(p, long), 'k-')
axis tight
title('Initial data')
xlabel('Longitude')
ylabel('Latitude')
subplot(212)
hold on;
plot(longLatRotated(1,:), longLatRotated(2,:),'.b-');
axis tight
title('Rotated data')
xlabel('Rotated x axis')
ylabel('Rotated y axis')
The angle you are looking for in the rotation matrix is the angle of the line makes to the horizontal. This can be found as the arc-tangent of the slope since:
tan(\theta) = Opposite/Adjacent = Rise/Run = slope
so t = atan(m) and noting that you want to rotate the line back to horizontal, define the rotation matrix as:
R = [cos(-t) sin(-t)
sin(-t) cos(-t)]
Now you can rotate your points with R