
4 %x = re sha p e ( x , [ 2 , 6 ] ) ;
5 N = s i z e ( x , 1 ) / 6 ;
6 x = res h ape ( x , [ 6 , N] ) ‘ ; % re sha p e from v e c t o r to matrix
7 %x = [ x ( 1 : 6 ) ‘ ; x ( 7 : end ) ‘ ] ;
8 dx ( : , 1 ) = x ( : , 4 ) ; % s e t v e l o c i t y i n x
9 dx ( : , 2 ) = x ( : , 5 ) ; % s e t v e l o c i t y i n y
10 dx ( : , 3 ) = x ( : , 6 ) ; % s e t v e l o c i t y i n z
11 f o r i = 1: s i z e ( x , 1)
12 dx ( i , 4 : 6 ) = 0 ;
13 f o r j = 1 : s i z e ( x , 1)
14 i f ( j~= i )
15 df = x ( j , 1 : 3 ) - x ( i , 1 : 3 ) ; % ge t d i f f e r e n c e between each p a i r ←-
o f p a r t i c l e s
16 dx ( i , 4 : 6 ) = dx ( i , 4 : 6 ) + GM*( d f ) /( d f * df . ‘ ) . ^ ( 3 / 2 ) ; % compute←-
g r a v i t a t i o n a l e f f e c t s
17 end
18 end
19 end
20 dx = re s hap e ( dx ‘ , [N*6 , 1 ] ) ; % ODE must output a column v e c t o r
21 end
In this code, ode113 is used instead of ode45 due to its improvement in accuracy. When
using ode45 to solve these equations, the round-off error in the implementation of the Runge-
Kutta method was causing the system to lose energy artificially over time. The ode113 method
is variable-step, variable order (VSVO) Adams-Bashforth-Moulton solver of orders 1 to 13, and
has been noted for its ability to be used in celestial mechanics problems (which is similar, if
not equivalent to this problem). Using this solver and the code in n_body.m, we generate the
micro-scale model that is necessary to perform equation-free modeling.
Listing 2: Matlab code – Micro-scale simulation
1 %% n - body problem s i m u l a t i o n
2
3 N = 5 0 ; % number o f bo d ie s
4 pdim = 3 ; % number o f s p a t i a l d i mensio n s
5 vdim = 3 ; % number o f v e l o c i t y dimens i o ns
6 vvar = 1 e0 ; % va r i a n c e f o r i n i t i a l v e l o c i t y of p a r t i c l e s
7 max = 1 e2 ; % max d i s t a n c e f o r i n i t a l p o s i t i o n s o f p a r t i c l e s
8
9 p o s i t i o n s = -max+(max+max) . * rand (N, pdim ) ;
10 v e l o c i t i e s = s q r t ( vvar ) * randn (N, vdim ) ;
11 i c = [ p o s i t i o n s , v e l o c i t i e s ] ;
12 i c = resh a pe ( i c . ‘ , [ 1 , N* 6 ] ) ;
13
14 % s e t time parameters
15 t_ st ar t = 0;
Assignment № 7 Page 2