Matlab中的3D绘图

时间:2011-11-12 23:31:18

标签: matlab

我试图通过将其从极坐标转换为笛卡尔坐标并使用surf()绘制它来绘制3D极坐标图的图形。

问题:我收到错误??? CData must be an M-by-N matrix or M-by-N-by-3 array。我哪里做错了?我是MATLAB的新手,不明白发生了什么。

MATLAB代码

全部清除;     关闭所有;

N=50;
%define matrices for ploting
x=zeros(N,N,N);
y=zeros(N,N,N);
z=zeros(N,N,N);
f=zeros(N,N,N);

%define basic input variables
r=linspace(0,2,N);
theta=linspace(0,pi,N);
phi=linspace(0,2.*pi,N);

for ii=(1:N) %use ii, jj to avoid confusion with the imaginary units
    for jj=(1:N)
        for kk=(1:N)
            x(ii,jj,kk)=r(ii).*sin(theta(jj)).*cos(phi(kk)); %%not using 
            %%for loop probably can work too, test later
            y(ii,jj,kk)=r(ii).*sin(theta(jj)).*sin(phi(kk));

            z(ii,jj,kk)=r(ii).*cos(theta(jj));

            f(ii,jj,kk)=r(ii).*exp(-r(ii)).*cos(theta(jj));
        end
    end
end

figure;
surf(x,y,z,f);
colormap([1,1,1]);

1 个答案:

答案 0 :(得分:1)

surf绘制一个曲面:所以每个(x,y)点都有一个高度z。

E.g。

N=50;
[X Y] = meshgrid(linspace(0,2,N));
Z = zeros(size(X));

for ii=(1:N)
    for jj=(1:N)
        x = X(ii,jj);
        y = Y(ii,jj);
        [theta, r] = cart2pol(x,y);
         Z(ii,jj) =r * exp(-r) * cos(theta);
    end
end

figure;
surf(X,Y,Z);