encoder in matlab

Hi for reading the position of encoder I have written a code in Matlab such as Arduino one but the problem is when the loop is running the counter (count) increasing or decreasing even when the encoder shaft is stopped! the code is:

a=arduino('COM3','Uno');
count=0;
aLast=readDigitalPin(a,'D2');
for i=1:1000
state=readDigitalPin(a,'D2');
if state~=aLast
if readDigitalpin(a,'D3')~=state
count = count+1
else
count = count-1
end
end
fprintf('count : %d/n',count)
pause(0.1)
end

Posting matlab code in an Arduino forum is probably not the best location…