Vectorization of Matlab Code involving ODE solver

2019-08-29 04:08发布

问题:

I want to write a fast MATLAB code where I need to write a for loop and I need to solve an ordinary differential equation each time.Is there any way to vectorize the code? Following is the part of the code:

       tspan=0:0.01:20;
        dw=rand(p,1);
        M0=repmat([0 0 1],p,1)';
        for p=1:ns
       [t,M(:,:,p)]=ode45(@(t,M) testfun(t,M,dw(p)),tspan,M0(:,p));
       end

where

       function  dM=testfun(t,M,w1) 
      M_x=M(1);
      M_y=M(2);
       M_z=M(3);
      dM=[w1*M_y;-w1*M_x+w1*M_z-2*w1*M_y;-w1*M_y-(1-M_z)];

回答1:

Try this and let me know how it works.

  • right hand side of the ODE system:

        function  dM = testfun(t,M,w1)
    
          dM = zeros(length(M), 1);
    
          M_x  =  M(1:3:end, 1);
          M_y  =  M(2:3:end, 1);
          M_z  =  M(3:3:end, 1);
    
         dM(1:3:end)  =              (w1.*M_y)';
         dM(2:3:end)  = (-w1.*M_x - 2*w1.*M_y + w1.*M_z)';
         dM(3:3:end)  =             (-w1.*M_y -  (1-M_z))';
       end
    
  • main program:

    clear all
    clc

    ns = input('Please tell me how many time you need to integrate the ODE system: ');

    tspan = 0:0.01:20;

    dw = rand(ns,1);

    M0 = repmat([0; 0; 1], 1, ns);

    [t, my_M] = ode45(@(t,my_M) testfun(t,my_M,dw), tspan, M0);

    s = size(my_M);

    for i = 1:ns

        M(:, 1:s(2)/ns, i) = my_M(:, s(2)/ns*(i-1)+1:s(2)/ns*i); 
    

    end