hey guys im trying to plot this in 3D but i keep getting an error, "Data cannot have more than 2 dimensions."

2 次查看(过去 30 天)
here is my code;
% 1) Compute the volume of a cylindrical shell with an inner radius
% r1=5,
% an outer radius
% r2=6, and length=10.
r1 = 5; %inner radius
r2 = 6; %outer radius
h = 10; %height
dr = 0.01;
dz = 0.1;
dphi = 0.01;
% set vector of iteration
r = [r1:dr:r2];
z = [0:dz:h];
phi = [0:dphi:2*pi];
noi_r = length(r);
noi_phi = length(phi);
noi_z = length(z);
x = zeros(noi_r,noi_phi,noi_z);
y = zeros(noi_r,noi_phi,noi_z);
z = zeros(noi_r,noi_phi,noi_z);
plot3(NaN,NaN,NaN,'.')
hold on
%initial volume
Volume =0;
for ir = 1:noi_r
for iphi = 1:noi_phi
for iz = 1:noi_z
dv = r(ir)*dphi*dz*dr;
Volume = Volume +dv;
x(ir,iphi,iz) = r(ir)*cos(phi(iphi));
y(ir,iphi,iz) = r(ir)*sin(phi(iphi));
z(ir,iphi,iz) = z(iz);
plot3(x,y,z,'.')
end
end
end
hold off
disp('volume is = ')
disp(Volume)

采纳的回答

David K.
David K. 2019-8-7
So the issue is that plot3 takes either a vector or a 2d matrix. Since you are plotting it as points you do not actually need to make your x,y, and z 3 dimensional. If you wanted you could have them as one long vector. So, to fix your issue you can do a few things. First, change your plot3 to
plot3(x(ir,iphi,iz),y(ir,iphi,iz),z(ir,iphi,iz),'.')
However, plotting this many times in a loop is extremely slow. Instead, after the loop you can do this
plot3(x(:),y(:),z(:),'.')
However, right now, your code will create a cylindrical shell at z = 0 and not have any height to it. This is because you are overwriting your z vector with zeros. I would suggest changing those names so you can have it be the proper height.
  3 个评论
David K.
David K. 2019-8-8
When I was testing before I just did z1. In the code I put the comments to point out what z affects. Since (5) had z(iz), it was expecting the z to still be assigned to (1). So to avoid overwriting it in (3) you have to change the previous z names to z1. Then, since you still want z1 in (5) you change that.
z1 = [0:dz:h];%%%%%% (1)
phi = [0:dphi:2*pi];
noi_r = length(r);
noi_phi = length(phi);
noi_z = length(z1);%%%%% (2)
x = zeros(noi_r,noi_phi,noi_z);
y = zeros(noi_r,noi_phi,noi_z);
z = zeros(noi_r,noi_phi,noi_z);%%%%%%% (3)
plot3(NaN,NaN,NaN,'.')
hold on
%initial volume
Volume =0;
for ir = 1:noi_r
for iphi = 1:noi_phi
for iz = 1:noi_z%%%%% (4)
dv = r(ir)*dphi*dz*dr;
Volume = Volume +dv;
x(ir,iphi,iz) = r(ir)*cos(phi(iphi));
y(ir,iphi,iz) = r(ir)*sin(phi(iphi));
z(ir,iphi,iz) = z1(iz);%%%%%%% (5)
end
end
end
plot3(x(:),y(:),z(:),'.')

请先登录,再进行评论。

更多回答(1 个)

boutros baqain
boutros baqain 2019-8-7
Thank you so much David k. I will try what you’ve suggested. Thank you!

类别

Help CenterFile Exchange 中查找有关 Lighting, Transparency, and Shading 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by