Error using surf Z must be a matrix, not a scalar or vector.

7 ビュー (過去 30 日間)
Peter
Peter 2024 年 2 月 21 日
編集済み: Hassaan 2024 年 2 月 21 日
I was trying to plot using the following code but i get this error. Please help me. Thank you!
x=(0:0.1:pi);
y=(0:0.1:pi);
[X, Y]= meshgrid(x,y);
Z=(sin(0.3*x)+(1+1./(1+cos(y).^2)));
surf(X, Y, Z);
Error using surf
Z must be a matrix, not a scalar or vector.

採用された回答

KSSV
KSSV 2024 年 2 月 21 日
編集済み: KSSV 2024 年 2 月 21 日
You have to use X and Y i.e matrix in the calculation Z.
x=(0:0.1:pi);
y=(0:0.1:pi);
[X, Y]= meshgrid(x,y);
Z=(sin(0.3*X)+(1+1./(1+cos(Y).^2)));
surf(X, Y, Z);

その他の回答 (1 件)

Hassaan
Hassaan 2024 年 2 月 21 日
編集済み: Hassaan 2024 年 2 月 21 日
To correct this, you need to use X and Y from the output of meshgrid in your calculation of Z, ensuring that Z is a matrix where each element corresponds to a combination of x and y values.
x = 0:0.1:pi;
y = 0:0.1:pi;
[X, Y] = meshgrid(x, y);
Z = sin(0.3*X) + (1 + 1./(1 + cos(Y).^2));
% Create the surface plot
surf(X, Y, Z);
% Add a title and axis labels
title('Surface Plot of Z = sin(0.3X) + (1 + 1./(1 + cos(Y).^2))');
xlabel('X axis');
ylabel('Y axis');
zlabel('Z axis');
% Add a colorbar to the figure to show the mapping of color to the Z values
colorbar;
sin(0.3*X) and cos(Y).^2 compute the sine and cosine values over the matrices X and Y, respectively, producing a matrix Z that matches the dimensions of X and Y. This makes Z suitable for plotting with surf. The key here is to use X and Y after they've been generated by meshgrid for any operations that contribute to the Z values.
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
Feel free to contact me.

カテゴリ

Help Center および File ExchangeLighting, Transparency, and Shading についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by