I’m a super beginner to MatLab, and I’m trying to debug a simple script I’m writing. I’m having a weird error while trying to debug my code. Here’s the script:
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
When I run the program, I get an Array Index Out of Bounds error on the line withM(p) = totOps(:,binM(p)+1);. I tried making sure the value of p was correct. On the first iteration through the for loop, binM(p) = 0. But when I try to get binM(p) + 1, I get 49. This is super weird.
Any help is much appreciated. I’m beating my head against the wall trying to figure out why this is happening.
Because binM(p) holds the ASCII value of the string ‘0’, not the actual double value 0. And ASCII value of ‘0’ is 48. ‘0’+1 is automatically converted to a double value. You do the rest of the math.