簡體   English   中英

在 Octave/Matlab 中輸入矩陣到 function 的尺寸

[英]Dimensions of input matrix to function in Octave/Matlab

我正在嘗試利用我自己的 Euler function 在 Octave 中使用常規 Euler 方法解決小型 ODE 系統。 我使它適用於 1x1 矩陣輸入,但我也想將它用於 2x2 矩陣輸入。

我的代碼如下所示:

 %Euler method for an ODE system of 2x2 matrix input (equation 1) and 1x1 input (equation 2)
 function [t,x,y]=Euler(f1,f2,t0,tf,x0,y0,n)
    h=(tf-t0)/n; %Constant step size
    t=t0:h:tf;
    x=[x0 x0] ; y=[y0]; %Starting values

    for j=1:n
       keulerf1=f1(t(j),x,y); %f1=dx/dt (from first equation) % I think the problem with dimensions might be here****
       keulerf2=f2(t(j),x,y); %f2=dy/dt (from second equation)
       x=x+h*keulerf1; %Euler forward method for first variable
       y=y+h*keulerf2; %Euler forward method for second variable
       OUT=[t(j+1) x y]
    endfor
 endfunction

例子:

 %Initial values:
 t0=0;tf=3;
 x0=10; %x(t0)
 y0=10; %y(t0)
 n=3;
 OUT_0=[t0 x0 x0 y0 y0]

 f1=@(t,x,y) [2*x 0]; %Equation 1 (arbitrary example): [dx/dt]=[2x 0]
 f2=@(t,x,y) [2*y]; %Equation 2 (arbitrary example): [dy/dt]=[2y]

 [t,x,y]=Euler(f1,f2,t0,tf,x0,y0,n)

  %It only works for f1, f2 of 1x1 size. I don't quite know why the dimensions aren't being consistent. 

感謝任何反饋。 祝你今天過得愉快。

如果我理解正確,您應該為您的 f1 使用矩陣注釋 A*x

這是歐拉:

function [t,x,y]=Euler(f1,f2,t0,tf,x0,y0,n)
    h=(tf-t0)/n; %Constant step size
    t=t0:h:tf;
    x=[x0]; % also define your two starting values better outside this function
    y=[y0]; %Starting values

    for j=1:n
       keulerf1=f1(t(j),x,y); %f1=dx/dt (from first equation)
       keulerf2=f2(t(j),x,y); %f2=dy/dt (from second equation)
       x=x+h*keulerf1; %Euler forward method for first variable
       y=y+h*keulerf2; %Euler forward method for second variable
       OUT=[t(j+1) x' y']
    endfor
 endfunction

這將是您的 function:

%Initial values:
 t0=0;tf=3;
 x0=[10 10]'; %x(t0)
 y0=10; %y(t0)
 n=3;
 OUT_0=[t0; x0; y0; y0]

 f1=@(t,x,y) [2 0; 0 0]*x;   %Equation 1 (arbitrary example): [dx/dt]=A*x
 f2=@(t,x,y) [2*y];          %Equation 2 (arbitrary example): [dy/dt]=[2y]

 [t,x,y]=Euler(f1,f2,t0,tf,x0,y0,n)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM