# How to modify a struct and create a new struct out of it?

7 views (last 30 days)
Rightia Rollmann on 4 Apr 2017
Answered: James Tursa on 4 Apr 2017
I want to get Cartesian coordinates from struct A
A(1).X = 1;
A(1).Y = 2;
A(1).Z = 3;
A(2).X = 4;
A(2).Y = 5;
A(2).Z = 6;
and change them to spherical coordinates in degrees and put them in struct B
for i = 1:length(A)
[theta,phi, r] = cart2sph(A(i).X, A(i).Y, A(i).Z);
B(i).r = r;
end
so I will finally get:
B(1).theta = 63.43;
B(1).phi = 53.30;
B(1).r = 3.7;
B(2).theta = 51.34;
B(2).phi = 43.13;
B(2).r = 8.77;
What is to shortest way to achieve it? For example, something without using this annoying for loop.

James Tursa on 4 Apr 2017
One way, but note there will be loops in the background:
X = [A.X];
Y = [A.Y];
Z = [A.Z];
[theta,phi,r] = cart2sph(X, Y, Z);
R = num2cell(r);
n = numel(A);
[B(1:n).theta] = deal(THETA{:});
[B(1:n).phi] = deal(PHI{:});
[B(1:n).r] = deal(R{:});
Also, note that keeping each individual number as its own field in a struct is not a very memory efficient way of storing your data. Unless you need the data in this format for some other reason, it would be better to simply keep the data as double arrays (e.g., like the X, Y, and Z arrays).