Search code examples
matlabplotmatlab-figuresurface

Generate a 3D surface plot by fitting over many 2D plots with varying z value


I would like to achieve a 3D surface plot. My outputs are as follows.

For a particular value of z, I get y for each value of x (x ranges like 0:0.1:1.4).

Then I vary z and, for the same range of x, I get y values.

The result can be visualised as 2D plots at discrete z values, consisting of the range of x and its corresponding y. Here is my original plot:

plot

I would like to create a 3D surface plot instead, like a blanket wrapped over the above 2D plots.


Solution

  • Here's an example for the two types of plots:

    figure
    hold on
    grid on
    view(30,40)
    x = 0:.01:4;
    z = .3:.3:3;
    y = NaN(numel(x), numel(z));
    for k = 1:numel(z)
        y(:,k) = abs((4-x).*sin(x/(1+z(k)))); % compute a vector as function output
            % for input vector x, for each z. Store as a column in matrix y
        plot3(x,repmat(z(k),size(x)),y(:,k)) % plot in 3D space
    end
    
    figure
    surf(x,z,y.','edgecolor','none') % surface plot
    view(30,40)
    grid on
    

    enter image description here

    enter image description here