# create multiple spheres at given coordinates using a for loop or function and function call

9 ビュー (過去 30 日間)
Nnamdi Chukwunenye 2020 年 9 月 1 日
Hi I have a set of coordinates that I would like to use to generate spheres on my plot. But I am struggling to write a for loop or function that executes this properly. if working properly i should get 4 new spheres from the coordinates in xyz. I have included the points and my attempt. Any help would be greatly appreciated.
xyz = [-8.67212090030965 -7.78294481282592 4.19809966191787
4.30363429770975 -6.33796132936349 2.30412196271579
11.4626419696253 3.31049523749869 2.84193335035400
1.28757516363600 6.20802478748340 11.1358580308193]
x1 = xyz(:, 1);
y1 = xyz(:, 2);
z1 = xyz(:, 3);
SizeXYZ = size(xyz,1);
for i = 1:SizeXYZ
createspheres(x1(i),y1(i),z1(i));
end
function createspheres(spherex, spherey, spherez)
[spherex, spherey, spherez] = sphere(4);
newroot
end

サインインしてコメントする。

### 採用された回答

You can use this code:
xyz = [-8.67212090030965 -7.78294481282592 4.19809966191787
4.30363429770975 -6.33796132936349 2.30412196271579
11.4626419696253 3.31049523749869 2.84193335035400
1.28757516363600 6.20802478748340 11.1358580308193]
x1 = xyz(:, 1);
y1 = xyz(:, 2);
z1 = xyz(:, 3);
SizeXYZ = size(xyz,1);
for i = 1:SizeXYZ
[x,y,z] = createspheres(x1(i),y1(i),z1(i));
surf(x,y,z);
hold on
end
%
function [X,Y,Z] =createspheres(spherex, spherey, spherez)
[x, y, z] = sphere(20);
X= x+ spherex;
Y = y+ spherey;
Z = z+spherez;
%newroot
end

#### 3 件のコメント

Nnamdi Chukwunenye 2020 年 9 月 2 日
Hi Asad, thanks for your solution it works perfectly, but now I am trying to store all the coordinates of all the spheres created during the loop and I am having trouble returning them to my workspace as a matrix. How would I go about doing that? Here is what Ive tried below, but it only returns the last set of sphere coordinates.
xyz = [-8.67212090030965 -7.78294481282592 4.19809966191787
4.30363429770975 -6.33796132936349 2.30412196271579
11.4626419696253 3.31049523749869 2.84193335035400
1.28757516363600 6.20802478748340 11.1358580308193];
x1 = xyz(:, 1);
y1 = xyz(:, 2);
z1 = xyz(:, 3);
SizeXYZ = size(xyz,1);
for i = 1:SizeXYZ
[x,y,z spheresXYZ] = createspheres(x1(i),y1(i),z1(i));
surf(x,y,z,'FaceColor', 'k');
hold on
end
%
function [X,Y,Z, spheresXYZ] =createspheres(spherex, spherey, spherez)
[x, y, z] = sphere(4);
X = x+spherex;
Y = y+spherey;
Z = z+spherez;
spheresXYZ = [X,Y,Z];
%newroot
end
You can make a 3d matrix and add x,y, and z to a layer(dimension) of the matrix.
allXYZ = zeros(4,3,SizeXYZ);
% 4 : size of points
% 3: x , y, and z
then in the loop you can have something like this:
allXYZ(:,:,i)= [x,y,z]; % if x is a vertical vector or [x', y', z'] for horizontal vectors
Nnamdi Chukwunenye 2020 年 9 月 3 日
Thank you!

サインインしてコメントする。

R2019a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by