MATLAB中的矩阵尺寸错误 [英] Matrix dimensions error in MATLAB

查看:195
本文介绍了MATLAB中的矩阵尺寸错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

太晚了-我找不到我的错误在error函数中的位置.我正在尝试参数估计.

It's late - I can't find where my error is in my error function. I'm attempting a parameter estimation.

function value = lv(t,y,p)
    %Lotka-Volterra Model
    %p(1)=a, p(2) = b, p(3) = c, p(4) = r.
    value = [-p(1)*y(1)-p(2)*y(1)*y(2);-p(4)*y(2)+p(3)*y(1)*y(2)];
end

function error = lverr(p)
    %LVERR: Function defining error function for
    %example with Lotka-Volterra equations.
    H = [30.0 47.2 70.2 77.4 36.3 20.6 18.1 21.4 22 25.4 27.1];
    L = [4 6.1 9.8 35.2 59.4 41.7 19 13 8.3 9.1 7.4];

    [t,y] = ode45(@lv,[0 10],[H(1);L(1)],[],p);
    value = (y(:,1)-H').^2+(y(:,2)-L').^2;
    %Primes transpose data vectors H and L
    error = sum(value);
end

以及我用来执行代码的主文件:

And the main filethat I use to execute the code:

clc; 
clear all;
format long;

H = [30.0 47.2 70.2 77.4 36.3 20.6 18.1 21.4 22 25.4 27.1];
L = [4 6.1 9.8 35.2 59.4 41.7 19 13 8.3 9.1 7.4];
guess = [0.47;0.024;0.023;0.76];
[p,error] = fminsearch(@lverr,guess);
[t,y]=ode45(@lv,[0 10],[30.0; 4.0],[],p);
subplot(2,1,1)
plot(t,y(:,1))
subplot(2,1,2)
plot(t,y(:,2))

这是错误:

??? Error using ==> minus
Matrix dimensions must agree.

Error in ==> lverr at 8
    value = (y(:,1)-H').^2+(y(:,2)-L').^2;

推荐答案

ode45积分器是一种自适应的步长大小可变的Runge-Kutta方法.这意味着在每个步骤中使用的步长取决于解决方案在该点的行为.这意味着输出[t,y]中的元素数量会因运行而有很大差异,因此永远不应依赖.

The ode45 integrator is an adaptive step-size, variable-order Runge-Kutta method. What this means is that the step size used at each step depends on the behaviour of the solution at that point. What this implies is that the number of elements in the output [t,y] will vary greatly from run to run, and should never be relied upon.

lverr(p)中,您希望获得这种积分结果与某些固定长度向量之间的差.这几乎总是失败的.您可以

In lverr(p), you want to take the difference between the result from such an integration, and some fixed-length vector. This will fail, practically always. You can

  1. 使用定步长积分器(不建议使用)
  2. 强制ode45仅在指定时间生成输出(调整tspan使其具有与H一样多的元素)
  3. 以某种在物理上有意义的意义对向量H(和L)进行插值.
  1. use a fixed-step integrator (never advisable)
  2. force ode45 to generate output only at specified times (adjust your tspan to have as many elements as H)
  3. Interpolate the vector H (and L) in some physically meaningful sense.

顺便说一句-请避免使用error作为变量名;它也是一个内置函数,可能会引起您和Matlab解释器的混淆.

As an aside -- please refrain from using error as a variable name; it's a built-in function too, which can lead to confusion for both you and the Matlab interpreter.

这篇关于MATLAB中的矩阵尺寸错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆