简体   繁体   English

在 Octave/Matlab 中输入矩阵到 function 的尺寸

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

I am trying to make use of my own Euler function to solve small ODE systems with regular Euler method in Octave.我正在尝试利用我自己的 Euler function 在 Octave 中使用常规 Euler 方法解决小型 ODE 系统。 I made it work for 1x1 matrix input, but I want to use it for 2x2 matrix input as well.我使它适用于 1x1 矩阵输入,但我也想将它用于 2x2 矩阵输入。

My code looks like this:我的代码如下所示:

 %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

Example:例子:

 %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. 

Appreciate any feedback.感谢任何反馈。 Have a nice day.祝你今天过得愉快。

If I understood it correctly, you should use matrix annotation A*x for your f1如果我理解正确,您应该为您的 f1 使用矩阵注释 A*x

This is the Euler:这是欧拉:

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

This would be your function:这将是您的 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