MATLAB: Create a colored surface based on scatter points - matlab

Using a dataset of the format [x,y,z,value], I can create a 3D scatter plot as shown in the images, where the color of each point at location (x,y,z) is based on value. Note that all of the images are of the same plot, just from different views. It is intended to be the surface of an octant of a sphere.
Is there a way I can do an interpolation of the colors in 3D such that we see a solid surface instead of individual points? I am looking for something along the lines of imagesc, but in 3D. I've tried a wide variety of functions, including scatteredInterpolant, patch, mesh, and surf, but those do not seem to work in 3 dimensions the way I'd like.

Based on your example data (with multiple shells), I put this program together. It uses trisurf so it doesn't need meshed data.
function PlotColoredSpheres(x,y,z)
tol = 0.01;
r = sqrt(x.^2 + y.^2 + z.^2);
data = num2cell(sortrows([r, x, y, z], [1,2,3,4]),1);
[R, X, Y, Z] = data{:};
figure(1)
RUnique = uniquetol(r, tol);
for Ru = RUnique(:)'
j = abs(R - Ru) < tol;
tri = delaunay(X(j),Y(j));
trisurf(tri, X(j), Y(j), Z(j));
lighting phong
shading interp
hold on
end
hold off
end

Related

MATLAB - 3D volume fill based on inequalities

I have three variables x, y and z. I have inequalities of the form
x >= a, y>= b, z>=c, x+y>=d, y+z>=e, x+z>=f, x+y+z>=g
where a to g are positive numbers. On a 3D plot with axes x, y and z, this is an open volume. I would like to fill the open side (i.e. away from 0) shape with color and show it in a plot. What is the way to do this on MATLAB?
I attempted to use fill3 and a mesh but the result was not very good
[x,y,z] = meshgrid(0:0.01:2,0:0.01:2,0:0.01:2);
ineq = (x>=1)& (y>0.5)&(z>=0.25)&(x+y>1.25)&(y+z>0.6)&(x+z>1.1)&(x+y+z>1.6);
fill3(x(:),y(:),z(:), 'r')
box on
grid on
Using plot3 also was not very good. Is there any other way to generate a nice 3D figure on MATLAB?
Mathematica does this using RegionPlot3D. I was hoping for a similar resultant image.
First of all, be careful when using 3D meshes, the one you defined contains 8M+ points.
Assuming your shape is convex, you can use convhull and trisurf:
Not that the option 'Simplify' is set as true to reduce the number of elements accounted for in the convex hull.
[x,y,z] = meshgrid(0:0.1:2,0:0.1:2,0:0.1:2);
ineq = (x>=1)& (y>0.5)&(z>=0.25)&(x+y>1.25)&(y+z>0.6)&(x+z>1.1)&(x+y+z>1.6);
figure;
x_ineq = x(ineq);
y_ineq = y(ineq);
z_ineq = z(ineq);
id_cvhl = convhull(x_ineq,y_ineq,z_ineq,'Simplify',true);
trisurf(id_cvhl,x_ineq,y_ineq,z_ineq,'FaceColor','cyan','edgecolor','none')
xlim([0 2])
ylim([0 2])
zlim([0 2])
In case you want the result to look a bit more than RegionPlot3D, don't use Simplify, and plot the edges (Be careful not too have a mesh with too many points!).
id_cvhl = convhull(x_ineq,y_ineq,z_ineq);
trisurf(id_cvhl,x_ineq,y_ineq,z_ineq,'Facecolor','yellow')

Creating meshgrid of scattered Cartesian data for plotting on a sphere

I have a set of n=8000 cartesian coordinates X,Y and Z as vectors and also a vector V of same size which I want to use as values to create a heatmap on a sphere.
I saw this link (visualization of scattered data over a sphere surface MATLAB), but I don't understand how I convert this set of data into a meshgrid for plotting using surf.
Almost every example I saw uses meshgrids.
Right now, I am doing by plotting a sphere and then use scatter3 to plot my points as big balls and try to smooth them later. I looks like this:
I would like to get the figure as the plotting of the example in that link, where he uses:
k = 5;
n = 2^k-1;
[x,y,z] = sphere(n);
c = hadamard(2^k);
surf(x,y,z,c);
colormap([1 1 0; 0 1 1])
axis equal
EDIT:
(Sorry for taking so long to reply, the corona crises kept away from work)
What I am actually doing is:
for i=1:numel(pop0n)
ori(i,:)=ori(i,:)/norm(ori(i,:));
end
x = ori(:,1);
y = ori(:,2);
z = ori(:,3);
%// plot
m=100;
[aa,bb,cc] = sphere(m);
surf(aa,bb,cc,ones(m+1,m+1)*min(pop0n))
hold on
colormap jet;
scatter3(x,y,z,400,pop0n/norm(pop0n),'filled');
colorbar
shading interp
The array 'ori' is 8000x3, and contains the x, y and z coordinates of the points I want to plot and pop0n is a 8000 sized vector with the intensities of each coordinate.
My main question is how do I transform my x, y, z and pop0n, that are vectors, into 2D arrays (meshgrid) to use surf?
Because I cannot simply do surf(x,y,z,pop0n) if they are vectors.
Thanks in advance
As David suggested, griddata does the job.
What I did was:
for i=1:numel(pop0n)
ori(i,:)=ori(i,:)/norm(ori(i,:));
end
x = ori(:,1);
y = ori(:,2);
z = ori(:,3);
%// plot
m=100;
[aa,bb,cc] = sphere(m);
v = griddata(x,y,z,pop0n,aa,bb,cc,'nearest');
surf(aa,bb,cc,v)
colormap jet;
colorbar
shading interp

Multiple 1D plots in a 3D plot

I have a 2D equation, for example y = sin(x + t). For each unique value of t, I would like to plot a 1D realization of y. For example, if x = 0:0.1:2*pi and t = 1:10, for each value of t I would like to plot y = sin(x + t) for x = 0:0.1:2*pi. Basically, I would like to have lines along one direction for each value of t.
Is there a way I can do this in MATLAB?
Would something like a waterfall plot be beneficial for your case? Given a vector of x coordinates, for each unique value of y (in your case t), it would plot a one-dimensional realization of that curve. First, you would generate a 2D grid of coordinates X, Y where each row of X and Y together would be a vector of x coordinates for one realization of y and you'd plot all of these together in one plot.
Something like this:
[t,x] = meshgrid(0:0.1:2*pi, 1:10);
waterfall(t, x, sin(x + t));
view(-50, 50); % Adjust for a better view
xlabel('x'); ylabel('t'); zlabel('y'); % Add axis labels
We get this plot:
If you don't desire the "vertical" baselines that you see in the plot, then you can get away with using surf by specifying some additional properties to it:
[t,x] = meshgrid(0:0.1:2*pi, 1:10);
surf(t, x, sin(x + t), 'FaceColor', 'white', 'EdgeColor', 'interp', 'MeshStyle', 'row');
view(-50, 50);
xlabel('x'); ylabel('t'); zlabel('y');
The FaceColor and EdgeColor attributes are there to mimic what you see in the waterfall plot. Each visualization has a white face and the amplitude colours are interpolated. What is important is the MeshStyle attribute where you want to display the edges of the plot row wise. The default way for mesh is to show both rows and columns, so you'll visualize your plot in a grid like pattern, which is not what you want. Setting MeshStyle to row will simulate the waterfall plot but without the vertical baselines that you see in that plot.
You'll get:

How to plot a surface with a texture map

I want to plot a surface with a texture map on it, but the conditions are not the "ideal" ones.
first lets explain what I have.
I have a set of points (~7000) that are image coordinates, in a grid. This points do NOT define perfect squares. IT IS NOT A MESHGRID. For the sake of the question, lets assume that we have 9 points. Lets ilustrate what we have with an image:
X=[310,270,330,430,410,400,480,500,520]
Y=[300,400,500,300,400,500,300,400,500]
Lets say we can get the "structure" of the grid, so
size1=3;
size2=3;
points=zeros(size1,size2,2)
X=[310,270,330;
430,410,400;
480,500,520]
Y=[300,400,500;
300,400,500;
300,400,500]
points(:,:,1)=X;
points(:,:,2)=Y;
And now lets say we have a 3rd dimension, Z.
EDIT: Forgot to add a piece if info. I triangulate the points in the image and get a 3D correspondence, so when displayed in a surface they don't have the X and Y coords of the image, for a simplification of the given data lets say X=X/2 Y=Y/3
And we have:
points=zeros(size1,size2,3)
Z=[300,330,340;
300,310,330;
290,300,300]
surf(points(:,:,1)/2,points(:,:,2)/3,points(:,:,3))
What I want is to plot the surface in 3D with the image texture. Each element should have the texture piece that have in the first image.
This needs to work for huge datasheets. I don't specially need it to be fast.
related post (but I has a meshgrid as initial set of points) : Texture map for a 2D grid
PD: I can post original images + real data if needed, just posted this because i think it is easier with small data.
You can use the texturemap property of surf which works with rectangular meshes as well as with non-rectangular ones.
Creating non-rectangular data points
% creating non-rectangular data points
[X, Y] = meshgrid(1:100, 1:100);
X = X+rand(size(X))*5;
Y = Y+rand(size(X))*5;
which results in the following data points:
Generating height data:
Z = sin(X/max(X(:))*2*pi).*sin(Y/max(Y(:))*2*pi);
Loading picture:
[imageTest]=imread('peppers.png');
and mapping it as texture to the mesh:
surf(X,Y,Z, imageTest, ...
'edgecolor', 'none','FaceColor','texturemap')
Note that, for the sake of demonstration, this non-rectangular grid is quite sparsely populated which results in a rather jagged texture. With more points, the result gets much better, irrespective of the distortion of the grid points.
Note also that the number of grid points does not have to match the number of pixels in the texture image.
~edit~
If X and Y coordinates are only available for parts of the image, you can adjust the texture accordingly by
minX = round(min(X(:)));
maxX = round(max(X(:)));
minY = round(min(Y(:)));
maxY = round(max(Y(:)));
surf(X,Y,Z, imageTest(minX:maxX, minY:maxY, :), ...
'edgecolor', 'none','FaceColor','texturemap')
I don't think you can do what you want with Matlab's built in commands and features. But using the technique from my other answer with a high-res version of the grid can do it for you.
By "high-res", I mean an interpolated version of the non-uniform grid with denser data points. That is used to sample the texture at denser data points so it can be drawn using the texturemap feature of surf. You can't use a normal 2D interpolation, however, because you need to preserve the non-uniform grid shape. This is what I came up with:
function g = nonUniformGridInterp2(g, sx, sy)
[a,b] = size(g);
g = interp1(linspace(0,1,a), g, linspace(0,1,sy)); % interp columns
g = interp1(linspace(0,1,b), g', linspace(0,1,sx))'; % interp rows
Note that you have to call this twice to interpolate the X and Y points independently. Here's an example of the original grid and an interpolated version with 10 points in each direction.
Here's how to use that high-res grid with interp2 and texturemap.
function nonUniformTextureMap
% define the non-uniform surface grid
X = [310,270,330; 430,410,400; 480,500,520];
Y = [300,400,500; 300,400,500; 300,400,500];
Z = [300,330,340; 300,310,330; 290,300,300];
% get texture data
load penny % loads data in variable P
% define texture grid based on image size
% note: using 250-550 so that a,b covers the range used by X,Y
[m,n] = size(P);
[a,b] = meshgrid(linspace(250,550,n), linspace(250,550,m));
% get a high-res version of the non-uniform grid
s = 200; % number of samples in each direction
X2 = nonUniformGridInterp2(X, s, s);
Y2 = nonUniformGridInterp2(Y, s, s);
% sample (map) the texture on the non-uniform grid
C = interp2(a, b, P, X2, Y2);
% plot the original and high-res grid
figure
plot(X(:),Y(:),'o',X2(:),Y2(:),'.')
legend('original','high-res')
% plot the surface using sampled points for color
figure
surf(X, Y, Z, C, 'edgecolor', 'none', 'FaceColor','texturemap')
colormap gray
I'm not sure I understand your question, but I think that what you need to do is sample (map) the texture at your grid's X,Y points. Then you can simply plot the surface and use those samples as colors.
Here's an example using the data you gave in your question. It doesn't look like much, but using more X,Y,Z points should give the result you're after.
% define the non-uniform surface grid
X = [310,270,330; 430,410,400; 480,500,520];
Y = [300,400,500; 300,400,500; 300,400,500];
Z = [300,330,340; 300,310,330; 290,300,300];
% get texture data
load penny % loads data in variable P
% define texture grid based on image size
% note: using 600 so that a,b covers the range used by X,Y
[m,n] = size(P);
[a,b] = meshgrid(linspace(0,600,n), linspace(0,600,m));
% sample (map) the texture on the non-uniform grid
C = interp2(a, b, P, X, Y);
% plot the surface using sampled points for color
figure
surf(X, Y, Z, C)
colormap gray

How to plot a second graph instead of color coding in matlab

i just started with my master thesis and i already am in trouble with my capability/understanding of matlab.
The thing is, i have a trajectory on a surface of a planet/moon whatever (a .mat with the time, and the coordinates. Then i have some .mat with time and the measurement at that time.
I am able to plot this as a color coded trajectory (using the measurement and the coordinates) in scatter(). This works awesomely nice.
However my problem is that i need something more sophisticated.
I now need to take the trajectory and instead of color-coding it, i am supposed to add the graph (value) of the measurement (which is given for each point) to the trajectory (which is not always a straight line). I will added a little sketch to explain what i want. The red arrow shows what i want to add to my plot and the green shows what i have.
You can always transform your data yourself: (using the same notation as #Shai)
x = 0:0.1:10;
y = x;
m = 10*sin(x);
So what you need is the vector normal to the curve at each datapoint:
dx = diff(x); % backward finite differences for 2:end points
dx = [dx(1) dx]; % forward finite difference for 1th point
dy = diff(y);
dy = [dy(1) dy];
curve_tang = [dx ; dy];
% rotate tangential vectors 90° counterclockwise
curve_norm = [-dy; dx];
% normalize the vectors:
nrm_cn = sqrt(sum(abs(curve_norm).^2,1));
curve_norm = curve_norm ./ repmat(sqrt(sum(abs(curve_norm).^2,1)),2,1);
Multiply that vector with the measurement (m), offset it with the datapoint coordinates and you're done:
mx = x + curve_norm(1,:).*m;
my = y + curve_norm(2,:).*m;
plot it with:
figure; hold on
axis equal;
scatter(x,y,[],m);
plot(mx,my)
which is imo exactly what you want. This example has just a straight line as coordinates, but this code can handle any curve just fine:
x=0:0.1:10;y=x.^2;m=sin(x);
t=0:pi/50:2*pi;x=5*cos(t);y=5*sin(t);m=sin(5*t);
If I understand your question correctly, what you need is to rotate your actual data around an origin point at a certain angle. This is pretty simple, as you only need to multiply the coordinates by a rotation matrix. You can then use hold on and plot to overlay your plot with the rotated points, as suggested in the comments.
Example
First, let's generate some data that resembles yours and create a scatter plot:
% # Generate some data
t = -20:0.1:20;
idx = (t ~= 0);
y = ones(size(t));
y(idx) = abs(sin(t(idx)) ./ t(idx)) .^ 0.25;
% # Create a scatter plot
x = 1:numel(y);
figure
scatter(x, x, 10, y, 'filled')
Now let's rotate the points (specified by the values of x and y) around (0, 0) at a 45° angle:
P = [x(:) * sqrt(2), y(:) * 100] * [1, 1; -1, 1] / sqrt(2);
and then plot them on top of the scatter plot:
hold on
axis square
plot(P(:, 1), P(:, 2))
Note the additional things have been done here for visualization purposes:
The final x-coordinates have been stretched (by sqrt(2)) to the appropriate length.
The final y-coordinates have been magnified (by 100) so that the rotated plot stands out.
The axes have been squared to avoid distortion.
This is what you should get:
It seems like you are interested in 3D plotting.
If I understand your question correctly, you have a 2D curve represented as [x(t), y(t)].
Additionally, you have some value m(t) for each point.
Thus we are looking at the plot of a 3D curve [x(t) y(t) m(t)].
you can easily achieve this using
plot3( x, y, m ); % assuming x,y, and m are sorted w.r.t t
alternatively, you can use the 3D version of scatter
scatter3( x, y, m );
pick your choice.
Nice plot BTW.
Good luck with your thesis.