Beginner: Using SURF Function, Error: Z must be a matrix, not a scalar or vector.

104 次查看(过去 30 天)
Hi,
I've never used the surf function before and I am getting this error that I do not understand. I've read the other posts on this and still can't figure out what I need to do.
My situation:
xA is 5001 x 1 double
yA is 5001 x 1 double
zA is 5001 x 1 double
What can't I just do [x,y] = meshgrid(xA,yA) then surf(x,y,zA)? I don't see what other info the function would need to make a surface. Can someone tell me how to get this working?

采纳的回答

Walter Roberson
Walter Roberson 2020-8-11
N = 250;
xvec = linspace(min(xA), max(xA), N);
yvec = linspace(min(yA), max(yA), N);
[X, Y] = ndgrid(xvec, yvec);
F = scatteredInterpolant(xA, yA, zA);
Z = F(X, Y);
surf(X, Y, Z, 'edgecolor', 'none');

更多回答(1 个)

Cris LaPierre
Cris LaPierre 2020-8-11
A surface is a 3D plot. All your X values are repeated for every Y value, and vice versa, meaning the surface is 5001 x 5001. Surf automatically can handle a vector for X and Y, but Z must be the matrix containing the Z value for every combination of X and Y.
Typically, you use meshgrid to create X and Y, then use those matrices to compute the values of Z.
Where you already have all 3, you likely need to reshape them to form matrices.
Otherwise, your data may not be a surface. Try something like scatter3 to see what it looks like.
  3 个评论
James Parkus
James Parkus 2020-8-11
Thank you very much for the info Cris and Walter. I needed that background info to understand how MATLAB works it versus how I think about it. I see the missing link, I'll do some more research to get a more solid understanding. Much appreciated!
Cris LaPierre
Cris LaPierre 2020-8-12
编辑:Cris LaPierre 2020-8-12
@Walter: That's why I said to use scatter3. This allows you to view the data first to see if it even could create a surface, or if it is just a line. It is possible to record all the points for a surface in a vector. If the result does end up looking like it could be a surface, then you might be able to just reshape the vectors into matrices that can be plotted using surf.
Here's a simple example so I don't completely lose James.
xA = [-1 -1 -1 -1 0 0 0 0 1 1 1 1];
yA = [-1 0 1 2 -1 0 1 2 -1 0 1 2];
zA = [2 1 2 5 1 0 1 4 2 1 2 5];
xB = reshape(xA,[4,3]);
yB = reshape(yA,[4,3]);
zB = reshape(zA,[4,3]);
figure
surf(xB,yB,zB)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Surface and Mesh Plots 的更多信息

标签

产品


版本

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by