MATLAB Answers

Store values generate in a function call in an array

2 ビュー (過去 30 日間)
Nnamdi Chukwunenye
Nnamdi Chukwunenye 2020 年 9 月 2 日
編集済み: Bruno Luong 2020 年 9 月 3 日
Hi I am trying to store the coordinates of the 4 spheres I am plotting from a function call. I can only return the final spheres coordinates instead of all of them. 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
[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];
end

  2 件のコメント

Rik
Rik 2020 年 9 月 2 日
I'm not sure I understand what you mean. Could you provide an example of what you want as the output?
Nnamdi Chukwunenye
Nnamdi Chukwunenye 2020 年 9 月 2 日
Hi, Rik so the code is generates 4 spheres, and I want an array (preferably a matrix, but from my attempts it might need to be a cell array) that contains all the coordinates of the 4 spheres.

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

採用された回答

Bruno Luong
Bruno Luong 2020 年 9 月 2 日
編集済み: Bruno Luong 2020 年 9 月 2 日
spheresXYZ = cell(1,SizeXYZ);
for i = 1:SizeXYZ
[x,y,z spheresXYZ{i}] = createspheres(x1(i),y1(i),z1(i));
...
end

  2 件のコメント

Nnamdi Chukwunenye
Nnamdi Chukwunenye 2020 年 9 月 2 日
Hey Bruno, why does the spheresXYZ have to be a cell array instead of a matrix?
Bruno Luong
Bruno Luong 2020 年 9 月 3 日
If you prefer storage 3D array (assuming the function returns always a fixed size output) you can get them like this at the end of the loop
spheresXYZ = cell(1,SizeXYZ);
for i = 1:SizeXYZ
...
end
spheresXYZ = cat(3, spheresXYZ{:});
Then when needed, each sphere #k coordinates can be obtained by
spheresXYZ(:,:,k)
There is a whole bunch of techniques to preallocate nd array (see e.g. Rik's answer) that can be adapted for each case. This topic is beyond this thread.

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

その他の回答 (1 件)

Rik
Rik 2020 年 9 月 3 日
Instead of using a cell array, you can also use a 3D matrix:
[~,~,~,spheresXYZ]=createspheres(0,0,0);spheresXYZ(1,1,SizeXYZ)=0;
for n = 1:SizeXYZ
[x,y,z,spheresXYZ(:,:,n)] = createspheres(x1(n),y1(n),z1(n));
end

  0 件のコメント

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

Community Treasure Hunt

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

Start Hunting!

Translated by