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

141 ビュー (過去 30 日間)
James Parkus
James Parkus 2020 年 8 月 11 日
編集済み: Cris LaPierre 2020 年 8 月 12 日
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 Center および File ExchangeSurface 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