0

我想编写一个快速的 MATLAB 代码,我需要编写一个 for 循环,并且每次都需要求解一个常微分方程。有没有办法对代码进行矢量化?以下是部分代码:

       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

在哪里

       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)];
4

1 回答 1

0

试试这个,让我知道它是如何工作的。

  • ODE 系统的右手边:

        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
    
  • 主程序:

    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

于 2013-03-17T14:57:48.207 回答