Search code examples
matlaboctavesurf

Defining surfaces not just in terms of z


I have three different surfaces and I want to display all of them in one figure.

The problem is, that I have one surface defined in terms of z (means that I got x and y values and a grid which specifies the z-values for each combination) and two other ones which are defined in terms of x. This means that there exist various z-values for one x,y-pair.

My idea was:

figure
surf(x,y,zgrid)
hold on
surf(x,ygrid,z)
surf(x,ygrid2,z)
hold off

I hoped MATLAB would manage it by itself but it doesn't. Do you have any ideas how to get the wanted results? I want to display all of them in one plot to show the cross-sections.

Here is an image of how it should more or less look like:

enter image description here

If there is a more beautiful method to display this, please let me know.


Solution

  • You didn't specify what exactly was going wrong, but I'll hazard an educated guess that you got an error like the following when you tried to plot your second surface:

    Error using surf (line 82)
    Z must be a matrix, not a scalar or vector.
    

    I'm guessing your x, y, and z variables are vectors, instead of matrices. The surf function allows for the X and Y inputs to be vectors, which it then expands into matrices using meshgrid. It doesn't do this for the Z input, though.

    It's best practice, in my opinion, to just use matrices for all your inputs anyway. Here's an example where I do this (using meshgrid) to plot three surfaces of a cube:

    % Top surface (in z plane):
    [x, y] = meshgrid(1:10, 1:10);
    surf(x, y, 10.*ones(10), 'FaceColor', 'r');
    hold on;
    
    % Front surface (in y plane):
    [x, z] = meshgrid(1:10, 1:10);
    surf(x, ones(10), z, 'FaceColor', 'b');
    
    % Side surface (in x plane):
    [y, z] = meshgrid(1:10, 1:10);
    surf(ones(10), y, z, 'FaceColor', 'g');
    axis equal
    

    And here's the plot:

    enter image description here