2012-02-14 148 views
2

我是MatLab的超級初學者,我正在嘗試調試我正在編寫的一個簡單腳本。在嘗試調試我的代碼時出現奇怪的錯誤。這裏的腳本:爲什麼0 + 1 == 49?

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.這太奇怪了。

任何幫助,非常感謝。我正在試圖弄清楚爲什麼會出現這種情況,我正在靠牆敲打我的頭。

+2

+1有趣的問題。 :) – yuk 2012-02-14 16:22:31

+1

標題是有點誤導。 – 2012-06-10 18:43:47

回答

8

由於binM(p)保存字符串'0'的ASCII值,而不是實際的雙倍值0.並且'0'的ASCII值是48.'0'+ 1自動轉換爲雙倍值。你做數學的其餘部分。

+0

想到這一點。謝謝! – Mason 2012-02-14 02:37:37

相關問題