Search code examples
matlabmatrixplotsurface

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.


Solution

  • 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:

    Eliminating Surf Portions

    Masks/Regions Not to be Plotted:

    Corresponding Regions

    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