Retain meshgrid structure when subsetting a meshgrid - matlab

When I subset an array constructed from meshgrid, I cannot work out how to keep its meshgrid structure. Thus, you cannot use it in a call to mesh or surface. I will demonstrate this in my example of constructing the unit sphere.
Possible alternate titles for this question:
How do you make the top half of the meshgrid sphere from scratch in Matlab?
How do you use mesh to plot a subset of a meshgrid?
This is motivated using the following toy example of constructing a sphere of unit radius in Matlab from scratch, so that it is like the one generated by:
[x, y, z] = sphere(100)
mesh(x, y, z)
Using the equation for a sphere:
Define a meshgrid and z to be:
x = linspace(-1, 1, 201);
y = linspace(-1, 1, 201);
[x, y] = meshgrid(x, y);
z = sqrt(1 - x.^2 - y.^2);
So far so good, except z takes imaginary values where the sphere does not exist over the xy-plane, that is, anywhere outside of the unit circle.
A call to mesh now returns an error:
>> mesh(x, y, z)
Error using mesh (line 58)
X, Y, Z, and C cannot be complex.
Thus, a logical step is to remove all complex values:
% get logical vector index where real z is
LI = z == real(z)
x = x(LI)
y = y(LI)
z = z(LI)
But now x, y, and z are no longer 3d arrays, and calling mesh gives another error:
>> mesh(x, y, z)
Error using mesh (line 58)
Z must be a matrix, not a scalar or vector.
So, in general I have no idea how to preserve the meshgrid structure when subsetting the data. Hence, I can't generate the top half of this sphere from scratch.

In general, you can "exclude" values from plotting while maintaining the matrix structure by using NaN value. In your case, try this:
LI = z == real(z);
z(~LI) = NaN;
mesh(x,y,z);

Related

Plotting a coloured 3D figure in MATLAB

I have 3 axes: X of size N, Y of size M and Z of size O, which correspond to the coordinates of my data.
I have a matrix: DATA of size MxNxO, which corresponds to the module for each points.
I would like to plot the MATLAB figure of coordinate X, Y, Z and color the point depending of the value of the matrix DATA of size MxNxO.
I tried lots of functions such as scatter3, surf, plot3, but none is working as I wanted.
This is what I tried:
n = 10;
x = linspace(0,10,n);
y = linspace(0,10,n);
z = linspace(0,10,n);
DATA = randn(n,n,n);
scatter3(x,y,z,DATA);
This code didn't work because DATA is not the same size as x, y, z. I also tried with:
[X,Y,Z] = ndgrid(x,y,z)
scatter3(X,Y,Z,DATA);
but this didn't work either.
The trick with scatter3() is to "unroll" your matrices to a column vector, and don't forget that the fourth argument is size, rather than colour:
n = 10;
x = linspace(0,10,n);
y = linspace(0,10,n);
z = linspace(0,10,n);
[X,Y,Z] = ndgrid(x,y,z);
DATA = randn(n,n,n);
% here 3 is the size. You can set it to a different constant, or vary it as well
scatter3(X(:), Y(:), Z(:), 3, DATA(:));
Results in
You can colour a surface, see its documentation, however, it doesn't seem to make much sense in your case, given you have a full cube of data points. A surface is 2D, whereas your data is 3D. For a 2D surface, simply follow the example in the docs:
n = 10;
x = linspace(0,10,n);
y = linspace(0,10,n);
Z = rand(n);
DATA = randn(n);
surf(x, y, Z, DATA);
Images rendered in R2007b, syntax cross-checked with the documentation.
If you've got a surface defined by an M -by- 4 array containing X, Y, Z and Data, you can use delaunay() to create a Delaunay triangulation of your points and then trisurf() to plot that. Note that this still requires a 2D surface, albeit it can vary in three dimensions. The cube of data in your example still doesn't make sense to plot as a surface, even with this method.

Plot a surface only for coordinates that satisfy a specific equation in MATLAB

I have two grid coordinates matrices, X and Y, created by calling [X, Y] = meshgrid(x, y), so their elements represent coordinates. How can I plot a surface on the xy-plane, using heights from matrix V, only for coordinates that satisfy a specific equation? For example, my plot extends up to radius a, but I dont want to plot any data to the set of points that satisfy the equation sqrt(x^2 + (y-c)^2) < b, where b, c (a>b) are given constants and x=X(i,j), y=Y(i,j). Is there an easy way to do this, other than creating the two grid coordinates matrices (up to radius a) and then manually removing elements from X, Y, V, using nested for loops? I have not found any way to limit the plotting area I am interested in by changing x, y.
Using Logical Indexing
Just in case you're still looking for any implementation details. Referencing the comment by #Ander Biguri. I have to add that it might be easier to use mesh parameters X and Y directly in the logical indexing. Here is a little playground script that might help future readers. Below Region_Array is a logical array that specifies where the condition in this case sqrt(X.^2 + (Y-c).^2) < b is true. When true Region_Array is indexed with the value "1" and elsewhere with "0". I've split this into two steps just in case the complementary region is quickly wanted. The images/plots below show the resulting surf() and masks/regions. MATLAB has some thorough documentation and examples overviewing logical indexing: Find Array Elements That Meet a Condition
Trivial Surface Plot:
Masks/Regions Not to be Plotted:
Playground Script:
%Random test axes%
x = linspace(0,100,50);
y = linspace(0,100,50);
[X,Y] = meshgrid(x,y);
%Trivial plot of ones%
V = ones(length(x),length(y));
%Constant parameters%
b = 20;
c = 10;
%Eliminating within the curved region%
figure(1)
Region_Array = sqrt(X.^2 + (Y-c).^2) < b;
V(Region_Array) = NaN;
subplot(1,2,1); surf(X,Y,V);
axis([0 100 0 100]);
title("Eliminating Within the Curved Region");
%Eliminating outside the curved region%
V = ones(length(x),length(y));
V(~Region_Array) = NaN;
subplot(1,2,2); surf(X,Y,V);
axis([0 100 0 100]);
title("Eliminating Outside the Curved Region");
figure(2)
subplot(1,2,1); imshow(~Region_Array,'InitialMagnification',200);
title("Region Array Mask/Map (Inside)")
subplot(1,2,2); imshow(Region_Array,'InitialMagnification',200);
title("Region Array Mask/Map (Outside)")
Ran using MATLAB R2019b

Z must be a matrix, not a scalaqr or vector, matlab

I am trying to make a 3d plot but i am getting an error and im not sure how to solve it. I know that there are other questions out there similar to mine but i tried some of them and it did not work.
fh = sin(x)*cos(y).^3 + 2*cos(x).^5*sin(y)
[X,Y] = meshgrid(1:0.5:10,1:20);
surf(X,Y,fh)
Error using surf (line 82)
Z must be a matrix, not a scalar or vector.
The Z data in this case is what you are passing to surf as fh. It looks like fh is the function you want to use to compute Z, but you need to use the gridded values you generated for X and Y to evaluate it. As your code is now, it is evaluating the function using x and y (case matters!), which you haven't defined for us. Try this instead:
[X, Y] = meshgrid(1:0.5:10, 1:20);
Z = sin(X).*cos(Y).^3 + 2.*cos(X).^5.*sin(Y);
surf(X, Y, Z);
Notice that I used the .* operator (element-wise multiplication) instead of the * operator (matrix multiplication) in the equation.
You could also do this by defining an anonymous function that evaluates the formula for a given set of data:
fh = #(x, y) sin(x).*cos(y).^3 + 2.*cos(x).^5.*sin(y);
[X, Y] = meshgrid(1:0.5:10, 1:20);
surf(X, Y, fh(X, Y));

Creating a surface correctly

I want to create and show the surface z=x*exp(-x^2-y^2) in the section x,y~[-10;10]. I am trying to use:
x=-10:10;
y=-10:10;
z=x*exp(-x^2-y^2);
[X,Y,Z]=meshgrid(x,y,z);
surf(X,Y,Z);
and getting:
"Error using ^
Inputs must be a scalar and a square matrix.
To compute elementwise POWER, use POWER (.^) instead."
I understand that x is a vector and so this is not a logical statement. Never the less, I do not have an Idea as to how to create this surface?
You'll want to use meshgrid before computing z so that you compute a value for z for each combination of x and y. Also you'll want to use element-wise operators (.^ and .*) to create z
% Create all permutations of x and y
[x, y] = meshgrid(-10:10,-10:10);
% Compute z for each permutation
z = x .* exp(-x.^2 - y.^2);
% Plot as a surface
surf(x, y, z)

Error in mesh(X,Y,Z) in matlab

This is my code:
load mwe16_2.dat;
x = mwe16_2(:,1); % x contains the 1st column(500 values) of ‘mwe16_2’
y = mwe16_2(:,2); % y contains the 2nd column (500 values)of ‘mwe16_2’
z = mwe16_2(:,3); % z contains the 3rd column(500 values) of ‘mwe16_2’
[X, Y, Z] = meshgrid (x, y, z);
mesh (X, Y, Z)
While running the code it is showing the error:
*Error in plot3_d (line 13) mesh(X,Y,Z) in Matlab*
Can someone say the reason for the error and how to correct it?
[X,Y,Z] = meshgrid(x,y,z) produces three 3D arrays from x, y and z vectors. Now if you take a look at mesh you will see that you are not providing this function with proper input.
If you want to illustrate the set of points defined by three vectors of x, y and z, you can consider using scatter3:
figure; scatter3(x, y, z)