Octave: Plotting results of 3D interpolation - plot

I want to plot a surface whose elevation is the result of 3D interpolation on scattered data:
I have coordinates x, y, z and the scalar value v in three column vectors. I would like to interpolate v on, say, a constant x plane with coordinates xi, yi, zi obtaining vi and eventually plot the surface (yi,zi,vi).
How can I do that?

Here comes the solution I have found, thanks to andy1978 on #octave irc channel and Nicola:
x1 = linspace (min(x),max(x),50) ;
y1 = linspace (min(y),max(y),50) ;
z1 = linspace (min(z),max(z),50) ;
[xx, yy, zz] = meshgrid (x1, y1, z1) ;
vv = griddata3 (x, y, z, v, xx, yy, zz ) ;
x0 = 0.05 ; % constant x of chosen plane
[~,i] = min (abs (x - x0)) ;
vv_sect = vv (:, i, :) ; % here I slice the matrix of interpolated results at x=x0
vv_out = squeeze (vv_sect) ; % and this is what I needed to reduce the dimensionality of
% the sliced matrix
[yy2,zz2] = meshgrid (y1, z1) ;
surf (yy2, zz2, vv_out ) ;

Related

Quaternion to matrix rotation only one axis

I have a quaternion that contains the rotation of the three axes (x, y, z) at the same time.
I want to convert this quaternion to a rotation matrix but only the rotation on the Y axis of the quaternion or of any of the other axes, without all three at the same time.
A possible route:
Transform unit vectors X=(1,0,0) and Z=(0,0,1) by the quaternion
Call these rotated vectors (x0,x1,x2) and (z0,z1,z2)
If the rotation would have been purely around Y, we would have:
(x0,x1,x2) = (cos(theta), 0, sin(theta))
(z0,z1,z2) = (-sin(theta), 0, cos(theta))
not used is (y0,y1,y2) = (0, 1, 0)
so, calculate
c = (x0+z2) / 2
and s = (x2-z0) / 2
then normalize to get c2 + s2 equal to 1
norm = sqrt(c * c + s * s)
if norm != 0:
c = c / norm
s = s / norm
(if the norm would be zero, there is not much we can do)
the angle would be atan2(c, s)
the rotation matrix would be [[c,0,-s],[0,1,0],[s,0,c]]

Finding the coordinates of a point contained by a trapezoid programmatically

If I have a trapezoid defined by four points (x1, y1), (x2, y2), (x3, y3), (x4, y4) (chosen as (255, 0), (255, 235), (200, 35), and (200, 235) for the sake of the example), and I divide it arbitrarily in n by m sections like so (pardon the crude drawing):
How could I find the coordinates of (x, y)?
I've tried fooling around with the slopes of the lines, but my math skills are too rusty to figure it out. Any ideas?
For the specific case as per your example it's quite straight forward.
First, the x location is easy. Since the verticals will always be parallel to the y axis, x is simply x width divided by the number of sections:
x = x1+((x2-x1)/a*xa)
where:
x = result coordinate
x1,x2 = edges of the trapezoid
a = number of sections
xa = x coordinate in term of sections
note: I chose a to avoid confusion with the symbol for slope: m.
For y it's a bit more complicated. We first need to find the coordinate that sits on the top and bottom lines of the trapezoid. We use the standard line equation for this:
y = mx+c
Finding m is simple. It's just Dy/Dx:
m = (y2-y1)/(x2-x1)
To get c we just substitute x, y and m into the formula:
c = y-mx
Once we get that, substitute the value of x found earlier into the formula to get the y coordinate. Do this twice to get the points on the top and bottom lines:
1 A 2
x------------x--------------x
| | |
| xC |
| | |
x------------x--------------x
3 B 4
All together (pseudocode):
coordinateFromSection (x1 y1 x2 y2 x3 y3 x4 y4 gridX gridY sectionX sectionY) {
xC = x1+((x2-x1)/gridX*sectionX)
// top line:
m = (y2-y1)/(x2-x1)
c = y1-(m*x1)
yA = m*xC + c
// bottom line:
m = (y4-y3)/(x4-x3)
c = y3-(m*x3)
yB = m*xC + c
// Find yC by dividing line AB by gridY
yC = yA+((yB-yA)/gridY*sectionY)
return (xC yC)
}
All the calculations above assume that (0,0) is the top left of the screen.

interpolation curve to surface

This is a interpolation problem:
I have a function z=z(x,y) and I know the relationship between x and y like x=f(y,x_0). Here x_0's are starting points of curves on time y=0. Let's assume x_0=[0 1 2] has three values. For each value of x_0, I get a curve in R^2.x1=f1(y),x2=f2(y) and x3=f3(y) and I draw z1,z2,z3 curves in R^3 using (x1,f1), (x2,f2) and (x3,f3). How can I interpolate z1,z2,23 for getting a surface?
I will be grateful for any help,
mgm
Using your notation, and some arbitrary example relationships for x = f(x0, y) and z = f(x,y), this is how you do it (I also added a plot of the direct calculation for reference):
% Define grid
x0_orig = 0:2;
y_orig = 0:3;
[x0, y] = meshgrid(x0_orig, y_orig);
% Calculate x (replace the relationship with your own)
x = x0 + 0.1 * y.^2;
% Calculate z (replace the relationship with your own)
z = 0.1 * (x.^2 + y.^2);
% Plot
subplot(1,3,1)
surf(x, y, z)
xlabel('x')
ylabel('y')
zlabel('z')
title('Original data')
%%%%%%%%%%
% Interpolate with finer grid
x0i = 0:0.25:2;
yi = 0:0.25:3;
xi = interp2(x0_orig, y_orig, x, x0i, yi');
[x0i yi] = meshgrid(x0i, yi);
zi = interp2(x0, y, z, x0i, yi);
subplot(1,3,2)
surf(xi, yi, zi);
title('Interpolated data')
%%%%%%%%%%
% Recalculate directly with finer grid
x0i = 0:0.25:2;
yi = 0:0.25:3;
[x0i yi] = meshgrid(x0i, yi);
xi = x0i + 0.1 * yi.^2;
zi = 0.1 * (xi.^2 + yi.^2);
subplot(1,3,3)
surf(xi, yi, zi)
title('Recalculated directly')

Which euler rotations can I use?

I have two Cartesian coordinates. There are xyz and BIG XYZ. I want to make these are parallel to each other. For example, x paralel to X ,y parallel to Y and z paralel to Z. I use a rotation matrix but I have a lot of different rotation matrices. For example I have 3D point in xyz Cartesian coordinates and it's called A and I want to change Cartesian coordinate to BIG XYZ and find the same 3D point in this coordinates its called B. Until now it is okay. But when I used a different rotational matrix, points were changed. What can I do? Which Euler rotations can I use?
Is this what you are looking for?
% an orthonormal base ('old')
x = [1; 0; 0];
y = [0; 1; 0];
z = [0; 0; 1];
% orthogonal (=rotation) matrix having this base as its columns
Rold = [x, y, z];
% another orthonormal base ('new')
X = [1; 1; 0]/sqrt(2);
Y = [-1; 1; 1]/sqrt(3);
Z = [1; -1; 2]/sqrt(6);
% orthogonal matrix having this basis as its columns
Rnew = [X, Y, Z];
% a "point" (indeed a vector; coordinates are with respect to the 'old' base,
% so this is actually the point 1*x + 2*y + 3*z)
A = [1; 2; 3]
% point = [x y z] A = [x y z] |1| = [X Y Z] |p| = [X Y Z] B
% |2| |q|
% |3| |r|
% where p,q,r are the unknown coordinates in the 'new' base
% To find them, just multiply by the inverse (=transpose) of [X Y Z]
B = Rnew'*Rold*A
% Rnew'*Rold, i.e. transpose(Rnew)*Rold is the rotation you are searching

Perpendicular on a line from a given point

How can I draw a perpendicular on a line segment from a given point? My line segment is defined as (x1, y1), (x2, y2), If I draw a perpendicular from a point (x3,y3) and it meets to line on point (x4,y4). I want to find out this (x4,y4).
I solved the equations for you:
k = ((y2-y1) * (x3-x1) - (x2-x1) * (y3-y1)) / ((y2-y1)^2 + (x2-x1)^2)
x4 = x3 - k * (y2-y1)
y4 = y3 + k * (x2-x1)
Where ^2 means squared
From wiki:
In algebra, for any linear equation
y=mx + b, the perpendiculars will all
have a slope of (-1/m), the opposite
reciprocal of the original slope. It
is helpful to memorize the slogan "to
find the slope of the perpendicular
line, flip the fraction and change the
sign." Recall that any whole number a
is itself over one, and can be written
as (a/1)
To find the perpendicular of a given
line which also passes through a
particular point (x, y), solve the
equation y = (-1/m)x + b, substituting
in the known values of m, x, and y to
solve for b.
The slope of the line, m, through (x1, y1) and (x2, y2) is m = (y1 - y2) / (x1 - x2)
I agree with peter.murray.rust, vectors make the solution clearer:
// first convert line to normalized unit vector
double dx = x2 - x1;
double dy = y2 - y1;
double mag = sqrt(dx*dx + dy*dy);
dx /= mag;
dy /= mag;
// translate the point and get the dot product
double lambda = (dx * (x3 - x1)) + (dy * (y3 - y1));
x4 = (dx * lambda) + x1;
y4 = (dy * lambda) + y1;
You know both the point and the slope, so the equation for the new line is:
y-y3=m*(x-x3)
Since the line is perpendicular, the slope is the negative reciprocal. You now have two equations and can solve for their intersection.
y-y3=-(1/m)*(x-x3)
y-y1=m*(x-x1)
You will often find that using vectors makes the solution clearer...
Here is a routine from my own library:
public class Line2 {
Real2 from;
Real2 to;
Vector2 vector;
Vector2 unitVector = null;
public Real2 getNearestPointOnLine(Real2 point) {
unitVector = to.subtract(from).getUnitVector();
Vector2 lp = new Vector2(point.subtract(this.from));
double lambda = unitVector.dotProduct(lp);
Real2 vv = unitVector.multiplyBy(lambda);
return from.plus(vv);
}
}
You will have to implement Real2 (a point) and Vector2 and dotProduct() but these should be simple:
The code then looks something like:
Point2 p1 = new Point2(x1, y1);
Point2 p2 = new Point2(x2, y2);
Point2 p3 = new Point2(x3, y3);
Line2 line = new Line2(p1, p2);
Point2 p4 = getNearestPointOnLine(p3);
The library (org.xmlcml.euclid) is at:
http://sourceforge.net/projects/cml/
and there are unit tests which will exercise this method and show you how to use it.
#Test
public final void testGetNearestPointOnLine() {
Real2 p = l1112.getNearestPointOnLine(new Real2(0., 0.));
Real2Test.assertEquals("point", new Real2(0.4, -0.2), p, 0.0000001);
}
Compute the slope of the line joining points (x1,y1) and (x2,y2) as m=(y2-y1)/(x2-x1)
Equation of the line joining (x1,y1) and (x2,y2) using point-slope form of line equation, would be y-y2 = m(x-x2)
Slope of the line joining (x3,y3) and (x4,y4) would be -(1/m)
Again, equation of the line joining (x3,y3) and (x4,y4) using point-slope form of line equation, would be y-y3 = -(1/m)(x-x3)
Solve these two line equations as you solve a linear equation in two variables and the values of x and y you get would be your (x4,y4)
I hope this helps.
cheers
Find out the slopes for both the
lines, say slopes are m1 and m2 then
m1*m2=-1 is the condition for
perpendicularity.
Matlab function code for the following problem
function Pr=getSpPoint(Line,Point)
% getSpPoint(): find Perpendicular on a line segment from a given point
x1=Line(1,1);
y1=Line(1,2);
x2=Line(2,1);
y2=Line(2,1);
x3=Point(1,1);
y3=Point(1,2);
px = x2-x1;
py = y2-y1;
dAB = px*px + py*py;
u = ((x3 - x1) * px + (y3 - y1) * py) / dAB;
x = x1 + u * px;
y = y1 + u * py;
Pr=[x,y];
end
Mathematica introduced the function RegionNearest[] in version 10, 2014. This function could be used to return an answer to this question:
{x4,y4} = RegionNearest[Line[{{x1,y1},{x2,y2}}],{x3,y3}]
This is mostly a duplicate of Arnkrishn's answer. I just wanted to complete his section with a complete Mathematica code snippet:
m = (y2 - y1)/(x2 - x1)
eqn1 = y - y3 == -(1/m)*(x - x3)
eqn2 = y - y1 == m*(x - x1)
Solve[eqn1 && eqn2, {x, y}]
This is a C# implementation of the accepted answer. It's also using ArcGis to return a MapPoint as that's what we're using for this project.
private MapPoint GenerateLinePoint(double startPointX, double startPointY, double endPointX, double endPointY, double pointX, double pointY)
{
double k = ((endPointY - startPointY) * (pointX - startPointX) - (endPointX - startPointX) * (pointY - startPointY)) / (Math.Pow(endPointY - startPointY, 2)
+ Math.Pow(endPointX - startPointX, 2));
double resultX = pointX - k * (endPointY - startPointY);
double resultY = pointY + k * (endPointX - startPointX);
return new MapPoint(resultX, resultY, 0, SpatialReferences.Wgs84);
}
Thanks to Ray as this worked perfectly for me.
c#arcgis
Just for the sake of completeness, here is a solution using homogeneous coordinates.
The homogeneous points are:
p1 = (x1,y1,1), p2 = (x2,y2,1), p3 = (x3,y3,1)
a line through two points is their cross-product
l_12 := p1 x p2 = (y1-y2, x2-x1, x1*y2 - x2*y1)
The (signed) distance of a point to a line is their dot product.
d := l_12 * p3 = x3*(y1-y2) + y3*(x2-x1) + x1*y2 - x2*y1
The vector from p4 to p3 is d times the normal vector of l_12 divided by the squared length of the normal vector.
n2 := (y1-y2)^2 + (x2-x1)^2
p4 := p3 + d/n2*(y1-y2, x2-x1, 0)
Note: if you divide l_12 by the length of the normal vector
l_12 := l_12 / sqrt((y1-y2)^2 + (x2-x1)^2)
the distance d will be the euclidean distance.
First, calculate the linear function determined by the points
(x1,y2),(x2,y2).
We get:
y1 = mx+b1 where m and b1 are constants.
This step is easy to calculate by the formula of linear function between two points.
Then, calculate the linear function y that goes through (x3,y3).
The function slope is -m, where m is the slope of y1.
Then calculate the const b2 by the coordinates of the point (x3,y3).
We get y2 = -mx+b2 where m and b2 are constants.
The last thing to do is to find the intersection of y1, y2.
You can find x by solving the equation: -mx+b2 = mx+b1, then place x in one of the equations to find y.
This is a vectorized Matlab function for finding pairwise projections of m points onto n line segments. Here xp and yp are m by 1 vectors holding coordinates of m different points, and x1, y1, x2 and y2 are n by 1 vectors holding coordinates of start and end points of n different line segments.
It returns m by n matrices, x and y, where x(i, j) and y(i, j) are coordinates of projection of i-th point onto j-th line.
The actual work is done in first few lines and the rest of the function runs a self-test demo, just in case where it is called with no parameters. It's relatively fast, I managed to find projections of 2k points onto 2k line segments in less than 0.05s.
function [x, y] = projectPointLine(xp, yp, x1, y1, x2, y2)
if nargin > 0
xd = (x2-x1)';
yd = (y2-y1)';
dAB = xd.*xd + yd.*yd;
u = bsxfun(#rdivide, bsxfun(#times, bsxfun(#minus, xp, x1'), xd) + ...
bsxfun(#times, bsxfun(#minus, yp, y1'), yd), dAB);
x = bsxfun(#plus, x1', bsxfun(#times, u, xd));
y = bsxfun(#plus, y1', bsxfun(#times, u, yd));
else
nLine = 3;
nPoint = 2;
xp = rand(nPoint, 1) * 2 -1;
yp = rand(nPoint, 1) * 2 -1;
x1 = rand(nLine, 1) * 2 -1;
y1 = rand(nLine, 1) * 2 -1;
x2 = rand(nLine, 1) * 2 -1;
y2 = rand(nLine, 1) * 2 -1;
tic;
[x, y] = projectPointLine(xp, yp, x1, y1, x2, y2);
toc
close all;
plot([x1'; x2'], [y1'; y2'], '.-', 'linewidth', 2, 'markersize', 20);
axis equal;
hold on
C = lines(nPoint + nLine);
for i=1:nPoint
scatter(x(i, :), y(i, :), 100, C(i+nLine, :), 'x', 'linewidth', 2);
scatter(xp(i), yp(i), 100, C(i+nLine, :), 'x', 'linewidth', 2);
end
for i=1:nLine
scatter(x(:, i)', y(:, i)', 100, C(i, :), 'o', 'linewidth', 2);
end
end
end

Resources