在科学计算等工作中,我们有时候在三维空间中,需要画出很多的空洞小球, 以展示我们的工作。但如何在3D空间中画出不同大小的小球,对于很多人而言还是蛮困难的。下面本人展示如何使用matlab中的sphere和surf函数,在三维空间中生成不同大小的球的例子。可以使用如下的代码!
参考:
1、sphere 球曲面函数详解
2、MATLAB】三维图形绘制 ( 绘制球面 | sphere 函数 | 设置光源 | light 函数 | 相机视线 | view 函数 )
3、MATLAB画三维球体函数
clear all
clc;
[x,y,z]=sphere(100);
hold on
% i=1;
% K=3;
for c11 = -0.8:0.4:0.8
for c12 = -0.8:0.4:0.8
for c13 = -0.8:0.4:0.8
surf(0.075*x-c11,0.075*y-c12, 0.075*z-c13,'LineStyle','none','FaceColor', 'r');
end
end
end
hold on
for c1 = -0.8:0.8:0.8
for c2 = -0.8:0.8:0.8
for c3 = -0.8:0.8:0.8
surf(0.125*x-c1,0.125*y-c2, 0.125*z-c3,'LineStyle','none','FaceColor', 'b');
end
end
end
hold on
camlight('headlight')
效果图如下:
三维旋转后,才可以看到如下效果。
上述代码只能生成[-1,1]X[-1,1]X[-1,1]空间中的小球,下面的代码为生成[0,1]X[0,1]X[0,1]空间中的小球。使用的命令为matlab中的 ellipsoid 。
clear all
clc
close all
% entorid3D = rand(10,3, 0.1,0.9);
for c11 = 0.05:0.3:0.95
for c12 = 0.05:0.3:0.95
for c13 = 0.05:0.3:0.95
[x1,y1,z1] = ellipsoid(c11, c12, c13, 0.05, 0.05, 0.05,100);
surf(x1,y1,z1,'LineStyle','none','FaceColor', 'r') %画出来球
axis equal %保证各个维度的长短一致
hold on
end
end
end
hold on
for c21 = 0.2:0.3:0.8
for c22 = 0.2:0.3:0.8
for c23 = 0.2:0.3:0.8
[x2,y2,z2] = ellipsoid(c21, c22, c23, 0.1, 0.1, 0.1,100);
surf(x2,y2,z2,'LineStyle','none','FaceColor', 'b') %画出来球
axis equal %保证各个维度的长短一致
hold on
end
end
end
hold on
axis([0 1 0 1 0 1]);
camlight('headlight')