其他...指数超过矩阵维度

时间:2011-11-28 04:07:12

标签: matlab

我在Matlab中真的是一个noobie,我正在制作一个程序。该程序只是尝试读取二进制数,例如(00011),前3个字符决定它将进行什么操作,其余的是要进入操作的那些(加,乘等)。但是一个错误一直在杀死我,“索引超过矩阵维度”,我明白matlab会自动将维度应用到矩阵中,这让我在背上烦恼......

这是代码。

function res = decPGL(varargin)
persistent rInicial
global r alto


if isempty(varargin)
   res = rInicial;
elseif isequal(varargin{1},'r') || isequal(varargin{1},'R')
   rInicial = varargin{2};
   res = rInicial;
else
   alto = 0;               % bandera que termina el programa
   programa = varargin{1}; % vector del programa completo
   ins = 1;                % número de instrucción que se va a ejecutar
   r = rInicial;           % estado inicial de registros


 while ins<=length(programa) && ~alto
    unPaso(programa(ins));
    ins = ins + 1;
 end
 res = r;
end



function unPaso(segmento)
% executes a segment of the program
global r alto

hh4 = ihighh(segmento,4);
i = ilow(ihighh(segmento,2),2)+1;
j = ilow(segmento,2)+1;
if hh4 <= 5
switch hh4
  case 0
     r(i) = r(i) + r(j);
  case 1
     r(i) = r(i) - r(j);
  case 2
     r(i) = r(i) * r(j);
  case 3
     if r(j) ~= 0
        r(i) = r(i)/r(j);
     end
  case 4
     r(i) = j;
  case 5
     t = r(i);
     r(i) = r(j);
     r(j) = t;
end
elseif hh4==6
switch i
  case 1
     r(j) = exp(r(j));
  case 2
     r(j) = log(abs(r(j)));
  case 3
     r(j) = r(j)^2;
  case 4
     r(j) = sqrt(abs(r(j)));
end
elseif hh4==7
switch i
  case 1
     r(j) = -r(j);
  case 2
     r(j) = sin(r(j));
  case 3
     r(j) = cos(r(j));
  case 4
     r(1) = r(j);
     alto = 1;
end
end

问题在于“r”变量,当在开关中并选择一个案例时,标记错误“索引超出矩阵尺寸”。

有任何想法或建议可以解决这个问题吗?

提前致谢。

PS:忘了把ihighh代码和i低......对不起......这里是....

 %%ihigh
function res = ihigh(p, m, varargin)
if length(varargin)>=1
    B = varargin{1};
else
    B = 2;
end

res = p - mod(p,B.^m);

%%ihighh
function res = ihighh(p, m, varargin)
if length(varargin)>=1
    B = varargin{1};
else
    B = 2;
end

res = ihigh(p,m,B)./(B.^m);

%%ilow
function res = ilow(p, m, varargin)

if length(varargin)>=1
   B = varargin{1};
else
   B = 2;
end

res = mod(p,B.^m);

1 个答案:

答案 0 :(得分:3)

我认为您的代码不完整。但无论如何,如果您自己调试代码会更有用。

在MATLAB中,这可以通过dbstop if error命令轻松完成。然后运行程序,只要发生未被捕获的错误,它就会切换到调试模式。然后,您应该手动调查r的大小以及您尝试访问的索引。这些将不匹配,因此您应该确定矩阵是否太小或您的索引是否在错误的范围内并且正确。

要退出调试模式,请输入命令dbquit并防止MATLAB自动切换到调试模式,只需运行dbclear if error

有关调试器的更多信息,请参阅MATLAB documentation