Using streamslice/quiver and inpolygon crop - matlab

Suppose we have quiver field i.e. we have a meshgrid and then we assign a vector to each point. Is it possible to plot only the quiver field within some polygon?
So in the figure below, we want everything outside the triangle to be cropped out.
Ideally the code will also be helpful for the next step of having multiple such polygons and cropping out everything on their complement.
Some approaches:
A direct way is to figure out the meshgrid for the particular polygon and then assign a vector to each point. But that will take a lot of time to figure out as polygons get more complicated. In other words, the regular meshgrid is the square polygon, so we must modify the meshgrid matrix depending on our polygon. A friend informed me of a mesh generator matlab code.
Use inpolygon. The input of inpolygon are points in (x,y). But in our case we only have the vector field assigned to a meshgrid. One idea is to solve the ode system to obtain concrete solution pairs (x,y) to plug into the polygon. But solving them takes a lot longer and the pictures are not as nice.

Here's some sample code which I think will generate the kind of plot you want. It uses inpolygon to "filter" out the points inside the polygon. The vector field is still evaluated at the original meshgrid points. It easily extends to multiple polygons too.
clear
clc
x = linspace(0, 1, 21);
[X,Y] = meshgrid(x,x);
U = -Y; %some velocity field
V = X;
hold off
quiver(X,Y,U,V); %quiver on all points
polygon = [0.2,0.2;
0.7,0.5;
0.5,0.8]; %polygon vertices
ind = inpolygon(X,Y,polygon(:,1),polygon(:,2)); %get indices of points inside polygon
hold on
quiver(X(ind),Y(ind),U(ind),V(ind)); %quiver of points inside polygon

Related

Graph different 2D ellipses in 3D axes at different heights in MATLAB

I want to graph different ellipses at different heights (z-coordinates).
My idea was to write the following code:
z=0:1/64:3/8;
t=linspace(-pi,pi,25);
[t,z]=meshgrid(t,z);
x=cos(-t);
y=cos(-t-4*pi*z);
I would like MATLAB to read my code like:
"Find x and y, and plot at the corresponding height (z). By doing so, join the points such that you'll form an ellipse at constant z".
I'm not sure what kind of function I could use here to do this and was hoping for someone to tell me if there exists such a function that will do the job or something similar.
In case you're wondering, I want to graph the polarization of light given two counterpropagating beams.
EDIT: While this is similar to the question draw ellipse and ellipsoid in MATLAB, that question doesn't address plotting 2D ellipses in 3D axes, which is what I am trying to do.
This can be solved by removing the meshgrid, and just using a plain old for-loop.
t = linspace(-pi,pi,25);
z = 0:1/64:3/8
f = figure;
hold on;
for i = 1:length(z)
x=cos(-t); y=cos(-t-4*pi*z(i));
plot3(x,y,z(i)*ones(length(z),1));
end
The problem in the original code is that you're trying build the ellipses all at once, but each ellipse only depends on a single z value, not the entire array of z values.
When I run this code, it produces the following plot:

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.

Matlab -plot a vector field

I have written a function in Matlab that gives me a vector at a position (x,y,z).
Now I am looking for the easiest way to make a colored map of this field on a grid and the color should be related to the norm of the vector.
What is the easiest way to define such a grid for $x \in [x_0,x_1],y \in [y_0,y_1], z \in [z_0,z_1]$? Probably linspace for each component would be possible, but maybe there is already a command that gives me the grid.
Now I need to evaluate my function. The problem is, that it actually gives me two vectors, but I am only interested in the first one. So when I first tried to do this I thought that $[A(i,j,k),~]=function(x(i),y(j),z(k))$ could work, but it did not(My goal was: Choose the first vector(A) and mark him with the reference(i,j,k), so that you later on know to which coordinates this vector belongs to).
So I am highly interested in any kind of ideas.
The function meshgrid might be what you are looking for to generate the x, y and z coordinates.
Instead of
[A(i,j,k),~]=function(x(i),y(j),z(k));
try
[A(i,j,k,:),~]=function(x(i),y(j),z(k));
so that you can fit the entire size of the 3-coordinate vector. Also, if you want to preallocate space use
A = zeros(Nx,Ny,Nz,3);
where Nx,... are the dims of your coordinate space. Then like #Moly explains, use meshgrid to generate a 3D grid,
[X Y Z] = meshgrid(x,y,z);
and loop or vectorize to resolve values of your function at points X(i,j,k),Y(i,j,k),Z(i,j,k), compute the norm and store it in 3D array C.
Edit
Representing a cube with mesh(X,Y,Z,C) is not possible but individual slices of the 3D cube can be visualized with mesh, setting the height Z equal to the result of the function C. Some additional work is then required to get coloring right.
Yet another alternative is to use pcolor or contourf. This is perhaps the easiest way to show the 4D data beyond creating a 3D isosurface.
code:
figure
colormap(jet)
for ii=1:9
subplot(3,3,ii)
pcolor(X(:,:,ii),Y(:,:,ii),F(:,:,ii))
axis('equal','square'), title(['Z=' num2str(ii)])
caxis([0 1])
end

Matlab 3d plot of indexed data

I am trying to plot a 3d view of a very large CT dataset. My data is in a 3d matrix of 2000x2000x1000 dimension. The object is surrounded by air, which is set to NaN in my matrix.
I would like to be able to see the greyscale value of the surface of the object (no isosurface) but I cannot quite work out how to do that in Matlab. Can anyone help me please?
Given that I a dealing with a huge matrix and I am only interested in the surface of the object, does anyone know a good trick how to reduce the size of my dataset?
The function surf(X,Y,Z) allows you to plot 3d data, where (X,Y) gives the coordinates in the x-y-plane while Z gives the z-coordinate and the surface color.
By default the function does not plot anything for the NaN entries, so you should be good to go with the surf function.
To set the surf-function to use a grayscale plotting use:
surf(matrix3d);
colormap(gray);
This plots the matrix in a surface plot and sets the colormap to grayscale.
In addition, as I understand your data, you might be able to eliminate entire plane-segments in your matrix. If for instance the plane A(1,1:2000,1:1000) is NaN in all entries you could eliminate all those entries (thus the entire Y,Z-plane in entry X=1). This will however require some heavy for loops, which might be over the top. This depends on how many data matrices you have compared to how many different plot you want for each matrix.
I will try to give you some ideas. I assume lack of a direct 3D "surface detector".
Since you have a 3D matrix where XY-planes are CT scan slices and each slice is an image, I would try to find edges of each slice say with edge. This would require some preprocessing like first thresholding each slice image. Then I can either use scatter3 to display the edge data as a 3D point cloud or delaunay3 to display the edge data as a surface.
I hope this will help you achieve what you are asking for.
I managed to get it working:
function [X,Y,Z,C] = extract_surface(file_name,slice_number,voxel_size)
LT = imread(file_name);%..READ THE 2D MAP
BW = im2bw(LT,1);%..THRESHOLD TO BINARY
B = bwboundaries(BW,8,'noholes');%..FIND THE OUTLINE OF THE IMAGE
X = B{1}(:,1);%..EXTRACT X AND Y COORDINATES
Y = B{1}(:,2);
indices = sub2ind(size(LT),X,Y);%..FIND THE CORRESPONDING LINEAR INDICES
C = LT(indices);%..NOW READ THE VALUES AT THE OUTLINE POSITION
Z = ones(size(X))*slice_number;
I can then plot this with
figure
scatter3(X,Y,Z,2,C)
Now the only thing I could improve is to have all these points in the scatter plot connected with a surface. #upperBound you suggested delaunay3 for this purpose - I cannot quite figure out how to do this. Do you have a tip?

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