draw an ellipse or contour in matlab - matlab

I have two vectors a = [1 1]' and b = [1 -1]' which are linearly independent.
I want to draw a shape like an ellipse or a contour around these points, so I can see the area which is spanned by these two vectors.
The picture below shows what I want to get. One of the blue vectors belongs to a and one of the red to b (I drew the mirrored vectors also for demonstration purpose). The green circle is what I want to draw.
How can I do that?

From your question and your example it seems to me that you don't have an entirely clear idea what you are trying to do. In order for MATLAB to plot anything, it will need at least a collection of points or an equation according to which this ellipse you want can be plotted.
The cleanest way to do so in this case would be to find the equations defining the ellipsoid. Using the information seen here, we see that we can describe any 2D-ellipse centered on the origin by the following equations:
x = a*cos(t)
y = b*sin(t)
The question then is: what should the values for our parameters a and b be? Since we have two points given that should satisfy these equations: [1,1] and [1,-1] we can deduce that a and b are equal to the square root of 2. Then we can plot the contour:
syms t % our equation's parameter is t
a = sqrt(2); b = sqrt(2);
x = a*cos(t);
y = b*sin(t);
ezplot(x,y) % plot the symbolic equation

Related

MATLAB: Area and centre of mass of a plotted figure

I have made a function that allows a user to draw several points and interpolate those points. I want the function to calculate the centre of mass using this vector :
I think I should therefore first calculate the area of the figure (I drew this example to illustrate the function output). I want to do this using Green's theorem
However since I'm quite a beginner in MATLAB I'm stuck at how to implement this formula in order to find the centre of mass. I'm also not sure how to get the data as my output so far is only the x- and y cordinates of the points.
function draw
fig = figure();
hax = axes('Parent', fig);
axis(hax, 'manual')
[x,y] = getpts();
M = [x y]
T = cumsum(sqrt([0,diff(x')].^2 + [0,diff(y')].^2));
T_i = linspace(T(1),T(end),1000);
X_i = interp1(T,x',T_i,'cubic');
Y_i = interp1(T,y',T_i,'cubic');
plot(x,y,'b.',X_i,Y_i,'r-')
end
The Center Of Mass for a 2D coordinate system should just be the mean of the interpolated x-coordinates and y-coordinates. The Interpolation should give you evenly spaced coordinates which you can use to your advantage. So simply add to your existing function:
CenterOfMass= [mean(X_i),mean(Y_i)]
plot(x,y,'b.',X_i,Y_i,'r-')
hold on
plot(CenterOfMass(1),CenterOfMass(2),'ro')
should give you the center of mass assuming that all points are weighted equally.

Data visualization - surface with parametric colour

I have a set of points in 3D in cartesian coordinates X,Y,Z. To every such point I associate a value which is stored in a vector C. I want to be able to colour the surface given by X,Y,Z with colors given by C. Alternatively, if possible, I would like to associate to each point a color from a finite number of given colors. In Matlab this is possible with surf(X,Y,Z,C), but X,Y must be in grid form (generated by meshgrid), not in general form, like in my case.
I managed to do this in the case of the sphere, but the procedure is not pretty, and it uses heavily the parametrization of the sphere. Here's an example of what I want to do (in the case of the sphere).
Is there a way to do this type of surface coloring in Matlab? (if it helps, I can also provide a triangulation of the surfaces in addition to the points X,Y,Z)
Is there another piece of software which can do similar things and can interface in some way with Matlab?
I based this off of Matlab's Representing Data as a Surface. Does this work?
xlin = linspace(min(x),max(x),33);
ylin = linspace(min(y),max(y),33);
[X,Y] = meshgrid(xlin,ylin);
f = scatteredInterpolant(x,y,z);
Z = f(X,Y);
g = scatteredInterpolant(x,y,c);
C = g(X,Y);
surf(X, Y, Z, C)
Thanks Ander Biguri for suggesting patch. Here's what I've come up with, and it seems to work fine.
function patch_color_plot(struc)
% struc is a structure containing at least the following:
% points - the coordinate of the points in a 3xN matrix
% t - the triangulation matrix
% x_0s - the point values
fac = struc.t;
vert = struc.points;
fvc = struc.x_0s;
p = patch('Faces',fac,'Vertices',vert,'FaceVertexCData',...
fvc,'FaceColor','interp');
set(p,'EdgeColor','none')
axis equal
axis off`
Here's a sample result:
and another one with a torus:
here's another example:

MeshGrid for Triangle Elements

I want to build a contourf plot of a certain aspect in my Plate. The plate is divided in triangle elements, which I have the coordinates (x,y) of each knot of the triangle.
So, How can I make a meshgrid for my knots so I can make my contourf plot?? I have the coordinates of everything and have the value of my function Z in each knot. (I'm a beginner in Matlab, sorry for this "basic" question)
If your goal is just to visualise the triangles then there is another way that's probably simpler and more robust (see the end of this post).
If you definitely need to generate contours then you will need to interpolate your triangular mesh over a grid. You can use the scatteredInterpolant class for this (documentation here). It takes the X and Y arguments or your triangular vertices (knots), as well as the Z values for each one and creates a 'function' that you can use to evaluate other points. Then you create a grid, interpolate your triangular mesh over the grid and you can use the results for the countour plot.
The inputs to the scatteredInterpolanthave to be linear column vectors, so you will probably need to reshape them using the(:)`notation.
So let's assume you have triangular data like this
X = [1 4; 8 9];
Y = [2 3; 4 5];
Z = [0.3 42; 16 8];
you would work out the upper and lower limits of your range first
xlimits = minmax(X(:));
ylimits = minmax(Y(:));
where the (:) notation serves to line up all the elements of X in a single column.
Then you can create a meshgrid that spans that range. You need to decide how fine that grid should be.
spacing = 1;
xqlinear = xlimits(1):spacing:xlimits(2);
yqlinear = ylimits(1):spacing:ylimits(2);
where linspace makes a vector of values starting at the first one (xlimits(1)) and ending at the third one (xlimits(2)) and separated by spacing. Experiment with this and look at the results, you'll see how it works.
These two vectors specify the grid positions in each dimension. To make an actual meshgrid-style grid you then call meshgrid on them
[XQ, YQ] = meshgrid(xqlinear, yqlinear);
this will produce two matrices of points. XQ holds the x-coordinates of every points in the grid, arranged in the same grid. YQ holds the y-coordinates. The two need to go together. Again experiment with this and look at the results, you'll see how it works.
Then you can put them all together into the interpolation:
F = scatteredInterpolant(X(:), Y(:), Z(:));
ZQ = F(XQ, YQ);
to get the interpolated values ZQ at each of your grid points. You can then send those data to contourf
contourf(XQ, YQ, ZQ);
If the contour is too blocky you will probably need to make the spacing value smaller, which will create more points in your interpolant. If you have lots of data this might cause memory issues, so be aware of that.
If your goal is just to view the triangular mesh then you might find trimesh does what you want or, depending on how your data is already represented, scatter. These will both produce 3D plots with wireframes or point clouds though so if you need contours the interpolation is the way to go.

measure valley width 2d, matlab

I have a 2d image, I have locations where local minimas occurs.
I want to measure the width of the valleys "leading" to those minimas.
I need either the radii of the circles or ellipses fitted to these valley.
An example attached here, dark red lines on the peaks contours is what I wish to find.
Thanks.
I am partially extending the answer of #Lucas.
Given a threshold t I would consider the points P_m that are below t and closer to a certain point m of minimum of your f (given a characteristic scale length r).
(You said your data are noisy; to distinguish minima and talk about wells, you need to estimate such r. In your example it can be for instance r=4, i.e. half the distance between the minima).
Then you have to consider a metric for each well region P_m, say for example
metric(P_m) = .5 * mean{ maximum vertical diameter of P_m ,
maximum horizontal diameter of P_m}.
In your picture metric(P_m) = 2 for both wells.
On the whole, in terms of pseudo-code you may consider
M := set of local minima of f
for_each(minimum m in M){
P_m += {p : d(p,m) < r and f(r)<t} % say that += is the push operation in a Stack
}
radius_of_region_around(m) = metric(P_m); %
I would suggest making a list of points that describe the values at the edge of your ellipse, perhaps by finding all the points where it crosses a threshold.
above = data > threshold
apply a simple edge detector
edges = EdgeDetector(above)
find coordinates of edges
[row,col] = find(edges)
Then apply this ellipse fitter http://www.mathworks.com/matlabcentral/fileexchange/3215-fitellipse
I'm assuming here you have access to the x, y and z data and are not processing a given JPG (or so) image. Then, you can use the function contourc to your advantage:
% plot some example function
figure(1), clf, hold on
[x,y,z] = peaks;
surf(x,y,z+10,'edgecolor', 'none')
grid on, view(44,24)
% generate contour matrix. The last entry is a 2-element vector, the last
% element of which is to ensure the right algorithm gets called (so leave
% it untouched), and the first element is your threshold.
C = contourc(x(1,:), y(:,1), z, [-4 max(z(:))+1]);
% plot the selected points
plot(C(1,2:end), C(2,2:end), 'r.')
Then use this superfast ellipse fitting tool to fit an ellipse through those points and find all the parameters of the ellipse you desire.
I suggest you read help contourc and doc contourc to find out why the above works, and what else you can use it for.

Getting intermediate points generated by plot() in MATLAB

I've got a series of XY point pairs in MATLAB. These pairs describe points around a shape in an image; they're not a function, meaning that two or more y points may exist for each x value.
I can plot these points individually using something like
plot(B(:,1),B(:,2),'b+');
I can also use plot to connect the points:
plot(B(:,1),B(:,2),'r');
What I'm trying to retrieve are my own point values I can use to connect the points so that I can use them for further analysis. I don't want a fully connected graph and I need something data-based, not just the graphic that plot() produces. I'd love to just have plot() generate these points (as it seems to do behind the scenes), but I've tried using the linseries returned by plot() and it either doesn't work as I understand it or just doesn't give me what I want.
I'd think this was an interpolation problem, but the points don't comprise a function; they describe a shape. Essentially, all I need are the points that plot() seems to calculate; straight lines connecting a series of points. A curve would be a bonus and would save me grief downstream.
How can I do this in MATLAB?
Thanks!
Edit: Yes, a picture would help :)
The blue points are the actual point values (x,y), plotted using the first plot() call above. The red outline is the result of calling plot() using the second approach above. I'm trying to get the point data of the red outline; in other words, the points connecting the blue points.
Adrien definitely has the right idea: define a parametric coordinate then perform linear interpolation on the x and y coordinates separately.
One thing I'd like to add is another way to define your parametric coordinate so you can create evenly-spaced interpolation points around the entire shape in one pass. The first thing you want to do, if you haven't already, is make sure the last coordinate point reconnects to the first by replicating the first point and adding it to the end:
B = [B; B(1,:)];
Next, by computing the total distance between subsequent points then taking the cumulative sum, you can get a parametric coordinate that makes small steps for points close together and larger steps for points far apart:
distance = sqrt(sum(diff(B,1,1).^2,2)); %# Distance between subsequent points
s = [0; cumsum(distance)]; %# Parametric coordinate
Now, you can interpolate a new set of points that are evenly spaced around the edge along the straight lines joining your points using the function INTERP1Q:
sNew = linspace(0,s(end),100).'; %'# 100 evenly spaced points from 0 to s(end)
xNew = interp1q(s,B(:,1),sNew); %# Interpolate new x values
yNew = interp1q(s,B(:,2),sNew); %# Interpolate new y values
These new sets of points won't necessarily include the original points, so if you want to be sure the original points also appear in the new set, you can do the following:
[sAll,sortIndex] = sort([s; sNew]); %# Sort all the parametric coordinates
xAll = [B(:,1); xNew]; %# Collect the x coordinates
xAll = xAll(sortIndex); %# Sort the x coordinates
yAll = [B(:,2); yNew]; %# Collect the y coordinate
yAll = yAll(sortIndex); %# Sort the y coordinates
EXAMPLE:
Here's an example to show how the above code performs (I use 11 pairs of x and y coordinates, one of which is repeated for the sake of a complete example):
B = [0.1371 0.1301; ... %# Sample data
0.0541 0.5687; ...
0.0541 0.5687; ... %# Repeated point
0.0588 0.5863; ...
0.3652 0.8670; ...
0.3906 0.8640; ...
0.4090 0.8640; ...
0.8283 0.7939; ...
0.7661 0.3874; ...
0.4804 0.1418; ...
0.4551 0.1418];
%# Run the above code...
plot(B(:,1),B(:,2),'b-*'); %# Plot the original points
hold on; %# Add to the plot
plot(xNew,yNew,'ro'); %# Plot xNew and yNew
I'd first define some parametric coordinate along the different segments (i.e. between the data points)
s = 1:size(B,1);
Then, just use interp1 to interpolate in s space. e.g. If you want to generate 10 values on the line between data point 5 and 6 :
s_interp = linspace(5,6,10); % parametric coordinate interpolation values
x_coord = interp1(s,B(:,1),s_interp,'linear');
y_coord = interp1(s,B(:,2),s_interp,'linear');
This should do the trick.
A.
Actually there is a MATLAB function "improfile", which might help you in your problem. Lets say these are the 4 coordinates which you want to find the locations between these coordinates.
xi=[15 30 20 10];
yi=[5 25 30 50];
figure;
plot(xi,yi,'r^-','MarkerSize',12)
grid on
Just generate a random image and run the function
n=50; % total number of points between initial coordinates
I=ones(max([xi(:);yi(:)]));
[cx,cy,c] = improfile(I,xi,yi,n);
hold on, plot(cx,cy,'bs-','MarkerSize',4)
Hope it helps