我是MatLab的超级初学者,我正在尝试调试一个我正在编写的简单脚本。我在尝试调试代码时遇到了一个奇怪的错误。这是脚本:
function [prob] = QuantumHW1(j,k,m)
X = [0 1; 1 0];
Y = [0 -sqrt(-1); sqrt(-1) 0];
Z = [1 0; 0 -1];
H = 1/sqrt(2) * [1 1; 1 -1];
S = [1 0; 0 i];
T = [1 0; 0 exp(sqrt(-1)*pi/4)];
mats = {X,Y,Z,H,S,T};
binJ = dec2bin(j,k);
binM = dec2bin(m,k);
totOps = {};
%Set up all the operators to be used
for p = 1:k
totOps(p) = mats(mod(p,6));
if p == 0
totOps(p) = X;
end
end
withM = {};
%Dot product with M
for p = 1:k
p
binM(p)+1
totOps(:,1)
withM(p) = totOps(:,binM(p)+1);
end
rTotal = 0;
%Now take components with respect to J
for p = 1:k
rTotal = rTotal + [not(binJ(p)),binJ(p)] * withM(p);
end
prob = norm(runningTotal)^2;
disp('The probability to measure j = %d in a k = %d system on input m = %d is %d',j,k,m,prob);
end
当我运行程序时,我在行withM(p) = totOps(:,binM(p)+1);
上得到一个数组索引超出界限错误。我试着确保p的值是正确的。在通过for循环的第一次迭代中,binM(p)= 0.但是当我尝试获得binM(p)+ 1时,我得到49.这非常奇怪。
非常感谢任何帮助。我正试图弄清楚为什么会发生这种情况,我正在撞墙。
答案 0 :(得分:8)
因为binM(p)保持字符串'0'的ASCII值,而不是实际的double值0.并且'0'的ASCII值是48.'0'+ 1自动转换为double值。你做其余的数学运算。