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

358 views (last 30 days)
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?

Accepted Answer

Walter Roberson
Walter Roberson on 11 Aug 2020
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');

More Answers (1)

Cris LaPierre
Cris LaPierre on 11 Aug 2020
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 Comments
Cris LaPierre
Cris LaPierre on 12 Aug 2020
Edited: Cris LaPierre on 12 Aug 2020
@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)

Sign in to comment.

Tags

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by