How to modify a struct and create a new struct out of it?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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).theta = rad2deg(theta);
B(i).phi = rad2deg(phi);
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.
0 commentaires
Réponses (1)
James Tursa
le 4 Avr 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);
THETA = num2cell(rad2deg(theta));
PHI = num2cell(rad2deg(phi));
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).
0 commentaires
Voir également
Catégories
En savoir plus sur Structures dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!