finding the intersection where multiple 3D parametric equations meet - matlab

I have some 3D parametric equations that I plot in matlab/octave and would like to find out where they intersect how can I go about doing this. Please note this is just a simple example I plan on having multiple parametric equations that will intersect.
What I'm trying to do is begin and end each plot at an intersection point.
My first thought was putting all the intersection points found at (t) into an array and plotting the ones I want I just couldn't figure out how to get the intersections at (t)
Example matlab/octave code below:
clear all, clf
t = 0:pi/60:2.45*pi;
plot3 ((t).*cos(t), (t).*sin(t), (t),'b*');
hold on
plot3 ((t).*sin((t)), (t).*cos((t)), (t),'r');
Here's an image with the arrows pointing to the intersecting points

I'd say that it is better to solve this system of equations analytically if possible.
Look, with your original code (just the plotted line styles were changed)
clear all, clf
t = 0:pi/60:2.45*pi;
plot3 ((t).*cos(t), (t).*sin(t), (t),'*b-');
hold on
plot3 ((t).*sin((t)), (t).*cos((t)), (t),'or-');
I have this picture at one of the intersections:
Its nice because the two plots intersect perfectly with each other in one of the plotted points.
Now consider the following situation. I changed your second line to
t = 0:0.05:2.45*pi;
Now I see this at the intersection point:
Now the two 3D polygonal lines generated for different values of t parameter in general case will not have any common points. So simple check for intersection of those linear segments will fail.
Same thing will happed if you update your equations to more complicated ones with more complicated dependencies over t (otherwise you are really lucky).
Analytical solution (if possible) will be unbeatable here.
As a numerical way to do this, consider distance D from an arbitrary point P1(x1(t1),y1(t1),z1(t1)) on one line to an arbitrary point P2(x2(t2),y2(t2),z2(t2)) on another one. Then find minimum of D as a function of two independent parameters t1 and t2. If D at minimum is zero (or very close to zero), then these two lines intersect. Otherwise they just pass each other.

Related

Matlab: discontinuous plot

I want to make a plot that discontinues at one point using Matlab.
This is what the plot looks like using scatter:
However, I would like to the plot to be a smooth curve but not scattered dots. If I use plot, it would give me:
I don't want the vertical line.
I think I can break the function manually into two pieces, and draw them separately on one figure, but the problem is that I don't know where the breaking point is before hand.
Is there a good solution to this? Thanks.
To find the jump in the data, you can search for the place where the derivative of the function is the largest:
[~,ind] = max(diff(y));
One way to plot the function would be to set that point to NaN and plotting the function as usual:
y(ind) = NaN;
plot(x,y);
This comes with the disadvantage of losing a data point. To avoid this, you could add a data point with value NaN in the middle:
xn = [x(1:ind), mean([x(ind),x(ind+1)]), x(ind+1:end)];
yn = [y(1:ind), NaN, y(ind+1:end)];
plot(xn,yn);
Another solution would be to split the vectors for the plot:
plot(x(1:ind),y(1:ind),'-b', x(ind+1:end),y(ind+1:end),'-b')
All ways so far just handle one jump. To handle an arbitrary number of jumps in the function, one would need some knowledge how large those jumps will be or how many jumps there are. The solution would be similar though.
you should iterate through your data and find the index where there is largest distance between two consecutive points. Break your array from that index in two separate arrays and plot them separately.

Using matlab to obtain the vector fields and the angles made by the vector field on a closed curve?

Here is the given system I want to plot and obtain the vector field and the angles they make with the x axis. I want to find the index of a closed curve.
I know how to do this theoretically by choosing convenient points and see how the vector looks like at that point. Also I can always use
to compute the angles. However I am having trouble trying to code it. Please don't mark me down if the question is unclear. I am asking it the way I understand it. I am new to matlab. Can someone point me in the right direction please?
This is a pretty hard challenge for someone new to matlab, I would recommend taking on some smaller challenges first to get you used to matlab's conventions.
That said, Matlab is all about numerical solutions so, unless you want to go down the symbolic maths route (and in that case I would probably opt for Mathematica instead), your first task is to decide on the limits and granularity of your simulated space, then define them so you can apply your system of equations to it.
There are lots of ways of doing this - some more efficient - but for ease of understanding I propose this:
Define the axes individually first
xpts = -10:0.1:10;
ypts = -10:0.1:10;
tpts = 0:0.01:10;
The a:b:c syntax gives you the lower limit (a), the upper limit (c) and the spacing (b), so you'll get 201 points for the x. You could use the linspace notation if that suits you better, look it up by typing doc linspace into the matlab console.
Now you can create a grid of your coordinate points. You actually end up with three 3d matrices, one holding the x-coords of your space and the others holding the y and t. They look redundant, but it's worth it because you can use matrix operations on them.
[XX, YY, TT] = meshgrid(xpts, ypts, tpts);
From here on you can perform whatever operations you like on those matrices. So to compute x^2.y you could do
x2y = XX.^2 .* YY;
remembering that you'll get a 3d matrix out of it and all the slices in the third dimension (corresponding to t) will be the same.
Some notes
Matlab has a good builtin help system. You can type 'help functionname' to get a quick reminder in the console or 'doc functionname' to open the help browser for details and examples. They really are very good, they'll help enormously.
I used XX and YY because that's just my preference, but I avoid single-letter variable names as a general rule. You don't have to.
Matrix multiplication is the default so if you try to do XX*YY you won't get the answer you expect! To do element-wise multiplication use the .* operator instead. This will do a11 = b11*c11, a12 = b12*c12, ...
To raise each element of the matrix to a given power use .^rather than ^ for similar reasons. Likewise division.
You have to make sure your matrices are the correct size for your operations. To do elementwise operations on matrices they have to be the same size. To do matrix operations they have to follow the matrix rules on sizing, as will the output. You will find the size() function handy for debugging.
Plotting vector fields can be done with quiver. To plot the components separately you have more options: surf, contour and others. Look up the help docs and they will link to similar types. The plot family are mainly about lines so they aren't much help for fields without creative use of the markers, colours and alpha.
To plot the curve, or any other contour, you don't have to test the values of a matrix - it won't work well anyway because of the granularity - you can use the contour plot with specific contour values.
Solving systems of dynamic equations is completely possible, but you will be doing a numeric simulation and your results will again be subject to the granularity of your grid. If you have closed form solutions, like your phi expression, they may be easier to work with conceptually but harder to get working in matlab.
This kind of problem is tractable in matlab but it involves some non-basic uses which are pretty hard to follow until you've got your head round Matlab's syntax. I would advise to start with a 2d grid instead
[XX, YY] = meshgrid(xpts, ypts);
and compute some functions of that like x^2.y or x^2 - y^2. Get used to plotting them using quiver or plotting the coordinates separately in intensity maps or surfaces.

Matlab : Intersect point of curves

Say for example I have data which forms the parabolic curve y=x^2, and I want to read off the x value for a given y value. How do I go about doing this in MATLAB?
If it were a straight line, I could just use the equation of the line of best fit to calculate easily, however I can't do this with a curved line. If I can't find a solution, I'll solve for roots
Thanks in advance.
If all data are arrays (not analytical expressions), I usually do that finding minimal absolute error
x=some_array;
[~,ind]=min(abs(x.^2-y0))
Here y0 is a given y value
If your data are represented by a function, you can use fsolve:
function y = myfun(x)
y=x^2-y0
[x,fval] = fsolve(#myfun,x0,options)
For symbolic computations, one can use solve
syms x
solve(x^2 - y0)
Assuming your two curves are just two vectors of data, I would suggest you use Fast and Robust Curve Intersections from the File Exchange. See also these two similar questions: how to find intersection points when lines are created from an array and Finding where plots may cross with octave / matlab.

Vertical line fit using polyfit

Its just a basic question. I am fitting lines to scatter points using polyfit.
I have some cases where my scatter points have same X values and polyfit cant fit a line to it. There has to be something that can handle this situation. After all, its just a line fit.
I can try swapping X and Y and then fir a line. Any easier method because I have lots of sets of scatter points and want a general method to check lines.
Main goal is to find good-fit lines and drop non-linear features.
First of all, this happens due to the method of fitting that you are using. When doing polyfit, you are using the least-squares method on Y distance from the line.
(source: une.edu.au)
Obviously, it will not work for vertical lines. By the way, even when you have something close to vertical lines, you might get numerically unstable results.
There are 2 solutions:
Swap x and y, as you said, if you know that the line is almost vertical. Afterwards, compute the inverse linear function.
Use least-squares on perpendicular distance from the line, instead of vertical (See image below) (more explanation in here)
(from MathWorld - A Wolfram Web Resource: wolfram.com)
Polyfit uses linear ordinary least-squares approximation and will not allow repeated abscissa as the resulting Vandermonde matrix will be rank deficient. I would suggest trying to find something of a more statistical nature.
If you wish to research Andreys method it usually goes by the names Total least squares or Orthogonal distance regression http://en.wikipedia.org/wiki/Total_least_squares
I would tentatively also put forward the possibility of detecting when you have simultaneous x values, then rotating your data about the origin, fitting the line and then transform the line back. I could not say how poorly this would perform and only you could decide if it was an option based on your accuracy requirements.

matlab interpolation

Starting from the plot of one curve, it is possible to obtain the parametric equation of that curve?
In particular, say x={1 2 3 4 5 6....} the x axis, and y = {a b c d e f....} the corresponding y axis. I have the plot(x,y).
Now, how i can obtain the equation that describe the plotted curve? it is possible to display the parametric equation starting from the spline interpolation?
Thank you
If you want to display a polynomial fit function alongside your graph, the following example should help:
x=-3:.1:3;
y=4*x.^3-5*x.^2-7.*x+2+10*rand(1,61);
p=polyfit(x,y,3); %# third order polynomial fit, p=[a,b,c,d] of ax^3+bx^2+cx+d
yfit=polyval(p,x); %# evaluate the curve fit over x
plot(x,y,'.')
hold on
plot(x,yfit,'-g')
equation=sprintf('y=%2.2gx^3+%2.2gx^2+%2.2gx+%2.2g',p); %# format string for equation
equation=strrep(equation,'+-','-'); %# replace any redundant signs
text(-1,-80,equation) %# place equation string on graph
legend('Data','Fit','Location','northwest')
Last year, I wrote up a set of three blogs for Loren, on the topic of modeling/interpolationg a curve. They may cover some of your questions, although I never did find the time to add another 3 blogs to finish the topic to my satisfaction. Perhaps one day I will get that done.
The problem is to recognize there are infinitely many curves that will interpolate a set of data points. A spline is a nice choice, because it can be made well behaved. However, that spline has no simple "equation" to write down. Instead, it has many polynomial segments, pieced together to be well behaved.
You're asking for the function/mapping between two data sets. Knowing the physics involved, the function can be derived by modeling the system. Write down the differential equations and solve it.
Left alone with just two data series, an input and an output with a 'black box' in between you may approximate the series with an arbitrary function. You may start with a polynomial function
y = a*x^2 + b*x + c
Given your input vector x and your output vector y, parameters a,b,c must be determined applying a fitness function.
There is an example of Polynomial Curve Fitting in the MathWorks documentation.
Curve Fitting Tool provides a flexible graphical user interfacewhere you can interactively fit curves and surfaces to data and viewplots. You can:
Create, plot, and compare multiple fits
Use linear or nonlinear regression, interpolation,local smoothing regression, or custom equations
View goodness-of-fit statistics, display confidenceintervals and residuals, remove outliers and assess fits with validationdata
Automatically generate code for fitting and plottingsurfaces, or export fits to workspace for further analysis