0

我想编写一个快速的MATLAB代码,我需要编写一个for循环,并且每次都需要求解一个常微分方程。是否有任何方法可以对代码进行矢量化? 以下是部分代码:在每次迭代中涉及ODE解算器的Matlab代码矢量化

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

回答

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

+0

谢谢了很多...对不起来晚了,感谢你...但它会帮助我反正... –

+0

下一个问题是......是有可能解决这个相同的系统,如果w1随时间步长而变化,无需在ODE函数中插入w1,因为它非常耗时 –