MATLAB: How to create randomly placed points within a 3D figure

3d figurefigurelimitspointsrandom points

So I have a function of a figure, and I am trying to generate at least a hundred points inside the figure. I have no problem generating the points itself but I can't seem to make them stay within the figure, some of the points go out of the figure which is not what I intended
clear;
close all;
clc;
%heart
[X,Y,Z]=meshgrid(-1.5:0.03:1.5);
F=(((X.^2) + (9/4).*(Y.^2) + Z.^2-1).^3+(-X.^2 .* Z.^3 -(9/80).*Y.^2.*Z.^3));%function defining a heart
patch(isosurface(X, Y, Z, F, 0), 'FaceColor', 'w', 'FaceAlpha',.3,'EdgeAlpha',.1);
view(3)
xlabel('x');
ylabel('y');
zlabel('z');
axis equal;
grid on;
%
hold on;
%random points
x = -1 + (1+1)*rand(1,100); %x-coordinate of a point
y = -0.6 + (0.6+0.6)*rand(1,100); %y-coordinate of a point
z = -0.8 + (1.2+0.8)*rand(1,100); %z-coordinate of a point
scatter3(x, y, z, 'MarkerFaceColor','b','MarkerEdgeColor','b');
hold off

Best Answer

Hello Frankie,
You have to select random points that are inside the heart and fortunately you already have the function that does that.
% pick plenty of random points
x = -1 + (1+1)*rand(1,500); %x-coordinate of a point
y = -0.6 + (0.6+0.6)*rand(1,500); %y-coordinate of a point
z = -0.8 + (1.2+0.8)*rand(1,500); %z-coordinate of a point
%function defining a heart
F1=(((x.^2) + (9/4).*(y.^2) + z.^2-1).^3+(-x.^2 .* z.^3 -(9/80).*y.^2.*z.^3));
ind = F1<0; % index for points inside the isosurface
x = x(ind); x = x(1:100); % pick 100 of those points
y = y(ind); y = y(1:100);
z = z(ind); z = z(1:100);
scatter3(x, y, z, 'MarkerFaceColor','b','MarkerEdgeColor','b');
hold off