矩阵乘法错误:矩阵维度必须一致

时间:2017-11-07 13:56:56

标签: matlab matrix matrix-multiplication

我有这段代码:

function main()
   a = 1.0e+04 * [0.005055052938847,0.010897917816899,0.022355965424711,0.043081981439108,0.077074049394439,0.127074049394439,0.193081981439108,0.272355965424711,0.360897917816899,0.455055052938847,0.552256864601221,0.650978664311931,0.750415022011379,0.850172973479352,0.950071110045004,1.050028912038499,1.150011648830086]
   B = 1.0e+04 * [1.215101736363023,0.697166188613023,0.400000000000000,0.229500515964941,0.131676217070435,0.075549399394941,0.043346565354951,0.024870147785673,0.014269279372341,0.008187017446000,0.004697311820178,0.002695088715947,0.001546310627203,0.000887197716963,0.000509030834515,0.000292057097908,0.000167568136653
   m = timeloop(a,B);
end

function m = timeloop(a,B)
   st = zeros(49,4);
   t = 0:0.001:0.05;
   for i = (1:49)
       st(i+1,1:4) = next_state(st(i,1:4),a,B,1e-4);
   end 
   m = mean(prod(state,2))
end

function next_state = next_state(state,alpha,beta,dt)
   nch = size(state,2);
   p01 = rand(1,nch);
   alphadt = repmat(alpha,1,nch)*dt;
   betadt = repmat(beta,1,nch)*dt;
   next_state1 = (p01<alphadt) .* (state==0);
   next_state0 = (p01<betadt) .* (state==1);
   next_state = state + next_state1 - next_state0;
end

但是它给了我以下错误:

  

矩阵尺寸必须达成一致。

     

q3>next_state中的错误(第59行)
      next_state1 = (p01<alphadt) .* (state==0);

     

q3>timeloop中的错误(第49行)
      st(i+1,1:4) = next_state(st(i,1:4),a,B,1e-4);

     

q3(第4行)中的错误       m = timeloop(a,B);

     

run中的错误(第86行)       evalin('caller', [script ';']);

我尝试将乘法更改为*而没有任何改进。我所看到的online似乎无法帮助我。我不太了解MATLAB,所以你必须在解释中非常具体。

1 个答案:

答案 0 :(得分:1)

如果你调试了代码,你很快就会意识到这个问题。

alpha中的

next_statea中的main相同,这意味着它的大小为1x3。

然后使用alphadt创建repmat(alpha,1,4),因此其大小为1x12。

然后尝试执行以下操作

(p01<alphadt) .* (state==0)
%   1x12      .*    1x3

由于错误明确指出,您的矩阵尺寸不一致。

因为你没有给出你想要达到的目标的任何背景,所以解决方案应该是什么并不明显。也许你想在repmat上使用state,或者在a上循环使用单个值。