使用* - 内部维度矩阵时出错必须同意

时间:2018-06-01 21:12:47

标签: matlab matrix ode

我遇到了一个问题,我必须比较解决ODE的方法:ode45,Euler和Gauss-Legendre方法。在这里,我必须计算不同步骤的错误。

  Error using  * 
  Inner matrix dimensions must agree.

  Error in untitled>@(t)t*(sin(t))

  Error in untitled (line 27)
    B = [-2*results(n-1) + sinus(t(n-1)+(1/2-sqrt(3)/6)*h);

它应该生成图表,比较不同步骤中不同方法的错误。但是出现了这样的错误:

=IFERROR(INDEX(A1:A4,1/MAX(INDEX((LEN(A1:D4)=0)/ROW(A1:D4),))),"No null values")

我找不到错误。我试过应用点('。'),但它没有奏效。我在哪里犯了错误?

2 个答案:

答案 0 :(得分:0)

Hash的使用肯定会解决问题。在此之后出现了第二个问题,这是因为您没有将变量.*编入索引。一旦你这样做,代码将完美运行。

答案 1 :(得分:0)

h=[0.01 0.05 0.1 0.5 1];
func = @(t, y) -2*y+t*sin(t);
opts = odeset('Reltol',1e-13,'AbsTol',1e-14,'Stats','on');
f1_f2_matrix = [];
sinus=@(t) t*(sin(t));
error2nd = zeros(length(h),1);
errorInf = zeros(length(h),1);
error2ndEuler = zeros(length(h),1);
errorInfEuler = zeros(length(h),1);


for i=1:length(h)
t=0:h(i):10;
euler = zeros(length(t),1);
fun_builtin = zeros(length(t),1);
t_builtin = zeros(length(t),1);
results = zeros(length(t),1);


%matrix for A=-2 and given h=0.01
matrix=[ 1-1/2*h(i), (1/2-sqrt(3)/3)*h(i); 
        (1/2+sqrt(3)/3)*h(i), 1-1/2*h(i)];


    for n=2:length(t)
    B = [-2*results(n-1) + sinus(t(n-1)+(1/2-sqrt(3)/6)*h(i));
         -2*results(n-1) + sinus(t(n-1) + (1/2+sqrt(3)/6)*h(i))];

%system of equations solution

    f1_f2_matrix = matrix\B; 

    results(n) = (results(n-1) + h(i)*0.5*(f1_f2_matrix(1) + f1_f2_matrix(2))); 

%euler
    euler(n) = euler(n-1)+h(i)*func(t(n-1),euler(n-1));

   end


%ODE45 FUNCTION
   [t_builtin,fun_builtin] = ode45(func, t, 0, opts);


%y'=-2y+tsin(t) errors
error2nd(i)=norm(fun_builtin-results)/norm(fun_builtin); %root mean square error of my function
errorInf(i)=norm((fun_builtin-results), Inf)/ norm((fun_builtin), Inf); %maximum error of my function

error2ndEuler(i)=norm(euler-results)/norm(fun_builtin); %root mean square error of my function (euler)
errorInfEuler(i)=norm((euler-results), Inf)/ norm((fun_builtin), Inf); %maximum error of my function (euler)

end

figure 
semilogy(h, error2nd, h, errorInf,h, error2ndEuler, h, errorInfEuler)
title([{('Dependence of root mean square and maximum errors')}; {('from h-step and method of solving differential equation')}])
legend('root mean square error: Gauss-Legendre of 4th order','maximum error: Gauss-Legendre of 4th order method','root mean square error: Euler method', 'maximum error: Euler method', 'Location', 'southeast');
xlabel('step');
ylabel('error');