How do you plot average of 3 arrays over time?

4 views (last 30 days)
Hello, I 'm still new to Matlab so any help would be appreciated.
I've been able to plot a propogation for the three body problem. I would like to include a plot for how the center of mass of the three bodies changes over time, too. In this problem the three masses are equal, so the center of mass would be the average of their positions at a given time.
Right now I have it setup that each of the positions x,y and z have their own arrays 5000 x 3. Each column, 1-3, corresponds to one of the three bodies and the rows is that x,y, or z positions as time changes.
My question is how can I take the average of each position, for the center of mass, and include it in the plot?
Thanks!
Example of my X array
0 1 2
0 1.00100000000000 2
1.25000000000000e-06 1.00200000000000 1.99999875000000
3.74800000798251e-06 1.00300000399998 1.99999624800001
etc.
How I'm plotting:
figure()
view([45 45 45 ])
hold on
plot3(x(:,1),y(:,1),z(:,1))
plot3(x(1,1),y(1,1),z(1,1),'r*')
plot3( x(:,2) ,y(:,2),z(:,2))
plot3(x(2,2),y(2,2),z(2,2),'r*')
plot3( x(:,3) ,y(:,3),z(:,3))
plot3(x(3,3),y(3,3),z(3,3),'r*')
xlabel('x')
ylabel('y')
zlabel('z')
legend('B1','B1 start','B2','B2 start','B3','B3 start')
grid on

Accepted Answer

Voss
Voss on 16 Jul 2022
First, a note about those starting position plots:
"Each column, 1-3, corresponds to one of the three bodies and the rows is that x,y, or z positions as time changes."
Then the starting position of the first body is
[x(1,1) y(1,1) z(1,1)]
(You have this correct in your plot.)
But the starting position of the second body is
[x(1,2) y(1,2) z(1,2)]
not
[x(2,2) y(2,2) z(2,2)]
which is what you have in your plot, and which is actually the position of the second body at time 2. (Similar for the third body / time 3.)
Now, to answer your question about the center of mass:
center_of_mass = [mean(x,2) mean(y,2) mean(z,2)]
mean(_,2) takes the mean of each row (dimension 2) of the given array. In this case, that's the mean of each body's x, then y, then z (for all rows of each matrix), concatenated together in a single matrix called center_of_mass. (Or you could define 3 separate variables for center of mass x-coordinate, center of mass y-coordinate, center of mass z-coordinate, but I won't do that.)
Then to plot the center of mass:
plot3(center_of_mass(:,1),center_of_mass(:,2),center_of_mass(:,3))
(Or if you just want to calculate it and plot it without storing it:)
plot3(mean(x,2),mean(y,2),mean(z,2))

More Answers (0)

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Tags

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!