Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab 3d surface plot from scatter3 data

Tags:

matlab

I want to plot a 3d scatter plot with a surface plot on the same figure, so that I end up with something like this:

enter image description here

I would have thought that the code below might have achieved what I wanted but obviously not. I have x, y and z data to plot a scatter3:

x = [1 1 1 1 0.95 0.95 0.95 0.95 0.85 0.85 0.85 0.85 0.8 0.8 0.8 0.8 0.75 0.75 0.75 0.75]';
y = [0.3 0.2 0.15 0.1 0.3 0.2 0.15 0.1 0.3 0.2 0.15 0.1 0.3 0.2 0.15 0.1 0.3 0.2 0.15 0.1]';
z = [0.1 0.15 0.2 0.3 0.1 0.15 0.2 0.3 0.1 0.15 0.2 0.3 0.1 0.15 0.2 0.3 0.1 0.15 0.2 0.3]';

scatter3(x,y,z)
hold on

And now add a surface??

p = [x y z];
surf(p)

Any ideas? Thanks.

like image 723
user2861089 Avatar asked May 14 '26 21:05

user2861089


1 Answers

The problem is that surf is treating your matrix p as a 2D array of z values, with integer values for x & y. Fortunately, surf has more than one way to enter values (see http://au.mathworks.com/help/matlab/ref/surf.html).

Try this:

x = [1 1 1 1 0.95 0.95 0.95 0.95 0.85 0.85 0.85 0.85 0.8 0.8 0.8 0.8 0.75 0.75 0.75 0.75]';
y = [0.3 0.2 0.15 0.1 0.3 0.2 0.15 0.1 0.3 0.2 0.15 0.1 0.3 0.2 0.15 0.1 0.3 0.2 0.15 0.1]';
z = [0.1 0.15 0.2 0.3 0.1 0.15 0.2 0.3 0.1 0.15 0.2 0.3 0.1 0.15 0.2 0.3 0.1 0.15 0.2 0.3]';

xr = reshape(x, 4, 5);
yr = reshape(y, 4, 5);
zr = reshape(z, 4, 5);

surf(xr, yr, zr)

xlabel('x')
ylabel('y')
zlabel('z')

In this case, surf expects a 2D array of x, y, and z values (as they would appear if looking at them top down). This way, surf knows which vertices to connect into a surface. Fortunately this can be easily achieved with your data by simply reshaping the vectors into matrices.

In future, if all your points lie on the same x and y coordinates, you could replace xr with [1, 0.95, 0.85, 0.8, 0.75] and yr with [0.3, 0.2, 0.15, 0.1] and surf will convert them into arrays for you.

like image 163
Jetfire Avatar answered May 18 '26 08:05

Jetfire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!