如何在MATLAB中可视化球体的交集?

时间:2016-11-10 07:11:25

标签: matlab visualization

似乎在一些地方(including on SO)提出了这个问题。我最近在可视化trilateration问题的结果时遇到了这个问题。

几乎在所有情况下,答案都会指示查询查看Wolfram for the math但不包括任何代码。数学真的是一个很好的参考,但如果我在编程问一个问题,一些代码也可能有所帮助。 (当代码问题的答案避免像#34这样简单的评论时,当然也很感激;编写代码很简单")。

那么如何在MATLAB中可视化球体的交集呢?我在下面有一个简单的解决方案。

1 个答案:

答案 0 :(得分:4)

我写了一个小脚本来做这件事。随意提出建议和编辑。它的工作原理是检查每个球体的表面是否落在所有其他球体的体积内。

对于球体交点,在sphere()函数调用中使用更多数量的面更好(但更慢)。这应该在可视化中给出更密集的结果。对于单独的球体可视化,较小的数字(~50)就足够了。请参阅有关如何可视化每个的评论。

close all
clear
clc

% centers   : 3 x N matrix of [X;Y;Z] coordinates
% dist      : 1 x N vector of sphere radii

%% Plot spheres (fewer faces)
figure, hold on % One figure to rule them all
[x,y,z] = sphere(50); % 50x50-face sphere
for i = 1 : size(centers,2)
    h = surfl(dist(i) * x + centers(1,i), dist(i) * y + centers(2,i), dist(i) * z + centers(3,i));
    set(h, 'FaceAlpha', 0.15)
    shading interp
end

%% Plot intersection (more faces)
% Create a 1000x1000-face sphere (bigger number = better visualization)
[x,y,z] = sphere(1000);

% Allocate space
xt = zeros([size(x), size(centers,2)]);
yt = zeros([size(y), size(centers,2)]);
zt = zeros([size(z), size(centers,2)]);
xm = zeros([size(x), size(centers,2), size(centers,2)]);
ym = zeros([size(y), size(centers,2), size(centers,2)]);
zm = zeros([size(z), size(centers,2), size(centers,2)]);

% Calculate each sphere
for i = 1 : size(centers, 2)
    xt(:,:,i) = dist(i) * x + centers(1,i);
    yt(:,:,i) = dist(i) * y + centers(2,i);
    zt(:,:,i) = dist(i) * z + centers(3,i);
end

% Determine whether the points of each sphere fall within another sphere
% Returns booleans
for i = 1 : size(centers, 2)
    [xm(:,:,:,i), ym(:,:,:,i), zm(:,:,:,i)] = insphere(xt, yt, zt, centers(1,i), centers(2,i), centers(3,i), dist(i)+0.001);
end

% Exclude values of x,y,z that don't fall in every sphere
xmsum = sum(xm,4);
ymsum = sum(ym,4);
zmsum = sum(zm,4);
xt(xmsum < size(centers,2)) = 0;
yt(ymsum < size(centers,2)) = 0;
zt(zmsum < size(centers,2)) = 0;

% Plot intersection
for i = 1 : size(centers,2)
    xp = xt(:,:,i);
    yp = yt(:,:,i);
    zp = zt(:,:,i);
    zp(~(xp & yp & zp)) = NaN;
    surf(xt(:,:,i), yt(:,:,i), zp, 'EdgeColor', 'none');
end

这是insphere函数

function [x_new,y_new,z_new] = insphere(x,y,z, x0, y0, z0, r)
    x_new = (x - x0).^2 + (y - y0).^2 + (z - z0).^2 <= r^2;
    y_new = (x - x0).^2 + (y - y0).^2 + (z - z0).^2 <= r^2;
    z_new = (x - x0).^2 + (y - y0).^2 + (z - z0).^2 <= r^2;
end

示例可视化

对于这些示例中使用的6个球体,在我的笔记本电脑上运行组合可视化平均需要1.934秒。

6个球体的交点: Intersection of 6 spheres

实际6个球体: not intersection

下面,我将两者结合起来,这样你就可以看到球体视图中的交叉点。 both

对于这些例子:

centers =

   -0.0065   -0.3383   -0.1738   -0.2513   -0.2268   -0.3115
    1.6521   -5.7721   -1.7783   -3.5578   -2.9894   -5.1412
    1.2947   -0.2749    0.6781    0.2438    0.4235   -0.1483

dist =

    5.8871    2.5280    2.7109    1.6833    1.9164    2.1231

我希望这可以帮助其他任何想要想象这种效果的人。