フィルターのクリア

I can not create a 3D object with the following code

2 ビュー (過去 30 日間)
Long
Long 2024 年 3 月 29 日
コメント済み: Long 2024 年 3 月 29 日
%Generate a volume-swept 3D object
N = 40; %number of increments
z = linspace (-5,5,N);
radius = sqrt(1 +z.^2);
theta = 2*pi*linspace(0,1,N);
X = radius.*cos(theta);
Y = radius.*sin(theta);
Z = z(:,ones(1,N));% <-- Do not understand the code? Create a matrix Z?
surf(X,Y,Z)
Error using surf (line 71)
Z must be a matrix, not a scalar or vector.
axis equal
Error: Z is not a matrix
Thanks in advance!

採用された回答

Cris LaPierre
Cris LaPierre 2024 年 3 月 29 日
編集済み: Cris LaPierre 2024 年 3 月 29 日
To create a surface, your Z input must contain a value for every X-Y combination organized in a grid (matrix). Columns correspond to X, rows correspond to y.
  • Here, z is a row vector
  • Z = z(:,ones(1,N)) is the same as z(:,[1 1 1 ... 1]) or repmat(z(:,1),1,N)
Use MATLAB to see what that code is doing:
N=4;
z = linspace (-5,5,N)
z = 1×4
-5.0000 -1.6667 1.6667 5.0000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
z(:,ones(1,N))
ans = 1×4
-5 -5 -5 -5
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
repmat(z(:,1),1,N)
ans = 1×4
-5 -5 -5 -5
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
It just repeats the first value of your vector N times.
I think you are not getting the results you expect because z is a row vector, not a column vector. Perhaps this is what you intended?
N = 40; %number of increments
z = linspace (-5,5,N)'; % use ' to turn z into a column vector
radius = sqrt(1 +z.^2);
theta = 2*pi*linspace(0,1,N);
X = radius.*cos(theta);
Y = radius.*sin(theta);
Z = z(:,ones(1,N));% <-- Do not understand the code? Create a matrix Z?
surf(X,Y,Z)
axis equal
If you did intend for z to be a vector, you can use any 3D plotting functino to view it. Here is a result using scatter3.
%Generate a volume-swept 3D object
N = 40; %number of increments
z = linspace (-5,5,N);
radius = sqrt(1 +z.^2);
theta = 2*pi*linspace(0,1,N);
X = radius.*cos(theta);
Y = radius.*sin(theta);
Z = z(:,ones(1,N));% <-- Do not understand the code? Create a matrix Z?
scatter3(X,Y,Z)
axis equal
  1 件のコメント
Long
Long 2024 年 3 月 29 日
I got it. Thanks a lot.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeObject Containers についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by