How to use TriScatteredInterp in MatLab? - matlab

I am having a problem with TriScatteredInterp in MatLab.
I am using a set of coordinate points with the corresponding temperature at that location. They are all in degrees in the form (long, lat, temp). I want to make an interpolant on these points so I can find out the values at other points and build a grid.
This is what I have done so far:
long = data(:,1)
lat = data(:,2)
values = data(:,3)
lat = lat.*(pi/180)
long = long.*(pi/180)
X = cos(lat).*cos(long)
Y = cos(lat).*sin(long)
Z = sin(lat)
F = TriScatteredInterp(X,Y,Z,values)
[long1 lat1] = meshgrid(-pi:pi/360:pi, -pi/2:pi/360:pi/2);
X1 = cos(lat1).*cos(long1)
Y1 = cos(lat1).*sin(long1)
Z1 = sin(lat1);
F.Method = 'natural'
InterpVals = F(X1,Y1,Z1);
mesh(long1, lat1, InterpVals)
As you can see for every (long, lat) point, I have computed the corresponding point on the sphere and have used the 3d version of TriScatteredInterp.
The problem is that the interpolation only works for the 'nearest' method, as for the linear or natural is producing just NaN's. As I have read this happens when the points that I want to interpolate are outside of the convex hull of the triangulation, but as the points needed are exactly on the sphere, and the input points are covering the entire range (Long : -180 to 180, Lat : -90 to 90), I just don't see how all the points could be outside the convex hull. Any help will be appreciated , ty.

You should interpolate values on the bi-dimensional original data (long, lat), not on the tri-dimensional one (X, Y, Z).
Note that I included some dummy data generator, for the readers that do not have access to your data()!
n = 100;
long = rand(n,1)*720-360;
lat = rand(n,1)*180-90;
values = rand(n,1)*30-5;
lat = lat.*(pi/180);
long = long.*(pi/180);
F = TriScatteredInterp(long,lat,values);
[long1 lat1] = meshgrid(-pi:pi/36:pi, -pi/2:pi/24:pi/2);
InterpVals = F(long1,lat1);
X1 = cos(lat1).*cos(long1);
Y1 = cos(lat1).*sin(long1);
Z1 = sin(lat1);
mesh(X1,Y1,Z1,InterpVals); %note here the meshing on the regular grid (X1,Y1,Z1)
There is still an issue on the edges of the map, as the interpolator doesn't know that the data "wraps" around. The content of InterpVals on those edges will be.. NaN!
Edit: suggestions for the wrapping:
1) rewrite TriScatteredInterp so that it uses modulos;
2) mirror the data around the "edges" of the map, interpolate, then crop it back to original size;
3) check out the Matlab Mapping Toolbox, which analyze and visualize geographic information.

Related

interpolating coordinates of 3D spline

I have a dataframe df1 containing points which describe a 3D curve (x, y, z coordinates and the arc length).
In a second data frame df2 I have the arc length (with different steps than in df1) and a value g. I need to find the g associated coordinates x, y and z.
My idea was to use splprep and splev to create a b_spline representation and interpolate via a Parametrization. Unfortunately this does not quite work, can someone help me?
Edit: This is my Code so far. I don't get any Errors, but the calculated x,y,z coordinates are wrong.
# df1 with x, y, z values and arc length
x = df1['x'].values
y = df1['y'].values
z = df1['z'].values
s = df1['arc_length'].values
# df2 with arc length intervals and gamma values
s_int = df2['arc_length'].values
gamma = df2['g'].values
# Use splprep to create a smooth curve
spl = splprep([x, y, z], s=0, k=3)
# Get the x, y, and z coordinates for a given arc length value
target_arc_lengths = s_int
points = splev(target_arc_lengths, spl[0])
x_coordinates = points[0]
y_coordinates = points[1]
z_coordinates = points[2]
Edit2: When creating the minimal example I noticed that my data is incorrect, the script works fine

Derivative on scatter data in Matlab

I have some data collected from a GPS network. My data consist of two arrays of the station coords (lat, long) and another two arrays populated with the vertical and the horizontal velocity of each station.
My script for interpolating is:
clear all; clc; format compact
load('lat_long_Ve_Vn.mat');
x = 34.5:0.1:42;
y = 19:0.1:28.5;
[Xq,Yq] = meshgrid(x,y);
Ve_i = griddata(lat,long,Ve,Xq,Yq);
Vn_i = griddata(lat,long,Vn,Xq,Yq);
I get the interpolated data for each node on my grid with two vectors, Ve_i and Ve_n
I want to calculate the following derivatives but I have no idea on how to do it.
I should mention that Vx is my Ve_i and Vy is my Vn_i, and I don't have a mathematical formula so I can calculate the derivatives with MuPAD. Any idea on how to do it?
If you use Gradient:
[Vxx Vxy] = gradient(Vx);
[Vyx Vyy] = gradient(Vy);

Programmatically producing polar or quasi-polar plots with a variable for color in matlab

I would like to create plots using matlab that represent a numerical assessment of quality in a radial fashion.
The best method I've found seems to not work properly. One runs the following code:
theta = (0 : (360/11) : 360)*pi/180;
r = 0 : 2 : 20 ;
[TH,R] = meshgrid(theta,r);
[X,Y] = pol2cart(TH,R);
Z = meshgrid(Data);
surf(X,Y,Z);
Data is a vector of data containing 11 numbers, an example dataset being the following:
Data = 0.884, 0.882, 0.879, 0.880, 0.8776, 0.871, 0.8587, 0.829, 0.811, 0.803, 0.780
the output of surf here is this:
I would like to produce a more refined version of this type of image:
which I have generated with the following code:
for theta = 0 : pi/100 : pi;
v = [InterpolatedImageHeight;LengthVector];
x_center = InterpolatedImageHeight((HorizontalRes+1)/2);
y_center = 0; %InterpolatedImageHeight((HorizontalRes+1)/2);
center = repmat([x_center; y_center], 1, length(InterpolatedImageHeight));
R = [cos(theta) -sin(theta); sin(theta) cos(theta)];
vo = R*(v - center) + center;
x_rotated = vo(1,:);
y_rotated = vo(2,:);
scatter(x_rotated,y_rotated,DotSize,InterpolatedData,'filled'); %x,y,area,color,properties
end
The issue with this is that it is a scatter plot where I am essentially using plot(r,Data), plotting many many copies, and increasing the dot size. The graphic itself has many seams, this takes an enormous amount of memory, and is time intensive where surf or mesh will run extremely fast and take minimal memory.
How does one produce concentric rings with a variable input for color?
There are two completely different plots in your question. The first one represents the data as rays from the origin towards the outside of the circle. The data-points are placed anti-clockwise. A refined version of this can be achieved like this:
Data = [0.884, 0.882, 0.879, 0.880, 0.8776, 0.871,...
0.8587, 0.829, 0.811, 0.803, 0.780];
theta = linspace(0,2*pi,length(Data));
r = linspace(0,20,length(Data));
[TH,R] = meshgrid(theta,r);
Z = meshgrid(Data);
[X,Y,Z] = pol2cart(TH,R,Z);
surf(X,Y,Z);
view(2);
shading interp
Note that I used linspace to generate theta and r to always match the length of Data. Z is also passed trough pol2cart. Then you can use shading interp to remove the lines between the patches and interpolate the color. With view(2) you can set the perspective as you would have a 2d-plot.
This is the result:
It's relatively easy to get a result like in your second example. There the data-points represent concentric circles around the origin and are placed from the origin towards the outside. Therefore, just transpose the meshgrid of Z by using the following line:
Z = meshgrid(Data)';
This is the result then:
based on the code by Darren Rowland in this thread I have come up with the following solution:
x = interp1(1:length(data),datax,(datax(1):datax(end)/f:datax(end)),'linear');
y = interp1(1:length(datay),datay,datay(1):datay(end)/f:datay(end),'spline');
theta = linspace(0,2*pi,n);
xr = x.'*cos(theta);
zr = x.'*sin(theta);
yr = repmat(y.',1,n);
figure;
surf(xy,yr,zr,zr*numcolors);
which is elegant, runs quickly, and produces beautiful figures. This is a sample of the output with some extra chart elements:

Retrieving data on coordinates which or not on the data grid through interpolation

I'm using Matlab to read a large (NetCDF) data set with information about a magnetic field. The data set is a three-dimensional array of 318x562x554 and I can retrieve have three one-dimensional array (318x1, 562x1 and 554x1) with each axis values of the coordinates. I would like to know the magnetic field values on points that do not fit on the data set grid. These points are in this case trajectory coordinates of a spacecraft placed in a two-dimensional array (3xn,n depends on how many coordinates you have).
x = ncread(file,'X_axis');
y = ncread(file,'Y_axis');
z = ncread(file,'Z_axis');
Bx = ncread(file,'Bx');
[x2,y2,z2] = meshgrid(y,x,z);
length = numel(interval_ET_5000);
Bx_intp = zeros(1,length);
for i = 1:length
[xi,yi,zi] = meshgrid(position_MEX_Mars_5000(1,i),...
position_MEX_Mars_5000(2,i),...
position_MEX_Mars_5000(3,i));
F = interp3(x2,y2,z2,Bx,xi,yi,zi);
Bx_intp(i) = F;
end
I have tried many things that didn't even work. This 'works' but not correct because the values in Bx_intp are way to high. Also because of the doing coordinates one at the time in a for loop makes it very slow, a normal run is about 3500 coordinates.
So basicly what I am looking for is a reverse scatteredInterpolant. This function accepts random data points and you interpolate the values on a meshgrid. But now I have a regular grid and I want interpolation on random points.
Thanks for the tip Ashish Uthama! I got it working with the code below. For other people with the same problem. You need ndgrid instead of meshgrid for griddedInterpolant and the coordinates need to be monotonic increasing.
x = ncread(file,'X_axis');
y = ncread(file,'Y_axis');
z = ncread(file,'Z_axis');
Bx = ncread(file,'Bx');
[x2,y2,z2] = ndgrid(x,y,z);
F = griddedInterpolant(x2,y2,z2,Bx,'linear','none');
Bx_intp = F(position_MEX_Mars_5000(1,i),...
position_MEX_Mars_5000(2,i),...
position_MEX_Mars_5000(3,i));

Point Cloud Generation

I have a 3-D geometrical shape which I have to convert into a point cloud.
The resultant point cloud can be considered equivalent to a point cloud output from a Laser Scan of the object.
No mesh generation is neeeded
The points generated may be evenly spaced, or maybe just randomly spaced - doesn't matter
The 3-D shape can be provided in the form of a 3-D mathematical formula
This has to be done using MATLAB
It's difficult to answer without an example but it sounds like you just want to perform a montecarlo simulation?
Lets say your shape is defined by the function f and that you have X, Y limits stored in two element vector e.g. xlim = [-10 10] i.e. all possible x values of this shape lie between x = -10 and x = 10 then I would suggest that you make f return some sort of error code if there is no value for a specific x-y pair. I'm going to assume that will be NaN. So f(x,y) is a function you are writing that either returns a z if it can or NaN if it can't
n= 10000;
counter = 1;
shape = nan(n, 3)
while counter < n
x = rand*diff(xlim) + mean(xlmin);
y = rand*diff(ylim) + mean(ylim);
z = f(x,y)
if ~isnan(z)
shape(counter, :) = [x, y, z];
counter = counter + 1
end
end
So the above code will generate 10000 (non unique, but that's easily adapted for) points randomly sample across your shape.
Now after typing this I realise that perhaps your shape is actually not all that big and maybe you can uniformly sample it rather than randomly:
for x = xlim(1):xstep:xlim(2)
for y = ylim(1):ystep:ylim(2)
shape(counter, :) = [x, y, f(x,y)];
end
end
or if you write f to be vectorized (preferable)
shape = [(xlim(1):xstep:xlim(2))', (ylim(1):ystep:ylim(2))', f(xlim(1):xstep:xlim(2), ylim(1):ystep:ylim(2));
and then either way
shape(isnan(shape(:, 3), :) = []; %remove the points that fell outside the shape
Here is the code to create a Cloud image with a Depth image from a PrimeSense Camera.
The input/Ouput of this function :
-inputs
depth -depth map
topleft -topleft coordinates of the segmented image in the whole image
-outputs
pclouds -3d point clouds
MatLab code :
depth = double(depth);
% Size of camera image
center = [320 240];
[imh, imw] = size(depth);
constant = 570.3;
% convert depth image to 3d point clouds
pclouds = zeros(imh,imw,3);
xgrid = ones(imh,1)*(1:imw) + (topleft(1)-1) - center(1);
ygrid = (1:imh)'*ones(1,imw) + (topleft(2)-1) - center(2);
pclouds(:,:,1) = xgrid.*depth/constant;
pclouds(:,:,2) = ygrid.*depth/constant;
pclouds(:,:,3) = depth;
distance = sqrt(sum(pclouds.^2,3));
Edit : This source is from this current article http://www.cs.washington.edu/rgbd-dataset/software.html
You can find some other Cloud function in MatLab and C++ that can be interest you.