Update on: How to model random non-overlapping spheres of non-uniform size in a cube using Matlab?
Posted
by
user3838079
on Stack Overflow
See other posts from Stack Overflow
or by user3838079
Published on 2014-08-04T21:01:12Z
Indexed on
2014/08/20
22:20 UTC
Read the original article
Hit count: 207
I am trying to use MATLAB for generating random locations for non-uniform size spheres (non-overlapping) in a cube. The for loop in the code below never seems to end. I don't know what am missing in the code. I have ran the code for no. of spheres (n) = 10; dims = [ 10 10 10 ]
function [ c r ] = randomSphere( dims )
% creating one sphere at random inside [0..dims(1)]x[0..dims(2)]x...
% radius and center coordinates are sampled from a uniform distribution
% over the relevant domain.
% output: c - center of sphere (vector cx, cy,... )
% r - radius of sphere (scalar)
r = rand(1); % you might want to scale this w.r.t dims or other consideration
c = r + rand( size(dims) )./( dims - 2*r ); % make sure sphere does not exceed boundaries
function ovlp = nonOverlapping( centers, rads )
% check if several spheres with centers and rads overlap or not
ovlp = false;
if numel( rads ) == 1
return; % nothing to check for a single sphere
end
dst = sqrt( sum( bsxfun( @minus, permute( centers, [1 3 2] ),...
permute( centers, [3 1 2] ) ).^2, 3) );
ovlp = dst >= bsxfun( @plus, rads, rads.' ); %' all distances must be smaller than r1+r2
ovlp = any( ovlp(:) ); % all must not overlap
function [centers rads] = sampleSpheres( dims, n )
% dims is assumed to be a row vector of size 1-by-ndim
% preallocate
ndim = numel(dims);
centers = zeros( n, ndim );
rads = zeros( n, 1 );
ii = 1;
while ii <= n
[centers(ii,:), rads(ii) ] = randomSphere( dims );
if nonOverlapping( centers(1:ii,:), rads(1:ii) )
ii = ii + 1; % accept and move on
end
end
© Stack Overflow or respective owner