
first = 1;
last = 256;

inputs=D;
inputs = double(inputs);
b=2;
inputs=inputs(:,b);

% predict the SubBytes output: SubBytes(XOR(key,data))

disp('Predicting intermediate values ...');
[m,n] = size(traces);

key = [0:255];
after_sbox = zeros(m,256);

for i=1:m
    after_sbox(i,:) = SubBytes(bitxor(inputs(i),key)+1);
end


key_trace = zeros(256,n);

    % predict the power consumption

    disp('Predicting the instantaneous power consumption ...');
    power_consumption = byte_Hamming_weight(after_sbox+1);
    
    % correlate the predicted power consumption with the real power
    % consumption
    disp('Generating the correlation traces ...');

    chunksize=50;
    chunks=n/50;
    for i=first:last
        for j=1:chunks
            cmatrix= corrcoef([traces(:,1+(j-1)*chunksize:j*chunksize)  power_consumption(:,i)]);
            key_trace(i,1+(j-1)*chunksize:j*chunksize) =cmatrix(chunksize+1,1:chunksize);
            
        end
    end

