Search code examples
matlabmachine-learningaccelerometerfeature-extractionpearson-correlation

How to calculate and save correlation coefficients in matlab?


I am working on pedestrian step detection (acceleration data), I want to calculate statistical features from my filtered signal. I have already calculated some and now i want to calculate correlation coefficients .

My data is of 1x37205 double. I calculated features using for loop with moving window size=2samples and 50% overlap of previous window. Below I am attaching the code I tried with to calculate corrcoef.

Now i want to check if it is the right way to calculate and also want to save the out put. I am unable to understand well that how to save all corrcoef's. Could some one guide me or provide any code help in matlab or how i can save?

%%Here M is mean and V is variance i already calculated from filtered data
    for i=window:length(M)-window
    C = corrcoef(M(i-window/2:i+window/2),V(i-window/2:i+window/2))
    end

Solution

  • Looking at the corrcoef documentation you can see that the output is a 2x2 matrix.

    The easiest way then to save all the coefficients would be to initialize your matrix C outside of the loop and then just assign values at each iteration. Perhaps something like

    C = zeros(2, 2, length(window:lenght(M)-window));
    for i = window:length(M) - window
        C(:, :, i) = corrcoef(M(i-window/2:i+window/2),V(i-window/2:i+window/2));
    end
    

    Even better, you can also see that the output of the corrcoef function is structured like this:

    [1, c1;
     c2, 1];
    

    where c1 and c2 are the actual coefficients. So you could also do:

    C = zeros(length(window:lenght(M)-window), 2);
    for i = window:length(M) - window
        temp = corrcoef(M(i-window/2:i+window/2),V(i-window/2:i+window/2));
        C(i, 1) = temp(1, 2); % "c1"
        C(i, 2) = temp(2, 1); % "c2"
    end
    

    EDIT TO ANSWER TO COMMENT

    To implement a sliding window with any size and with any overlap, you might want to change the indexing:

    wdwSize = 2;
    overlap = 0.5;
    
    C = zeros(length(1:wdwSize*overlap:length(A)-wdwSize*overlap), 2);
    
    for i = 1:wdwSize*overlap:length(A)-wdwSize*overlap
        window = i:i+wdwSize - 1;
        temp = corrcoef(M(window), V(window));
        C(i, 1) = temp(1, 2); % "c1"
        C(i, 2) = temp(2, 1); % "c2"
    end
    

    In your case wdwSize*overlap is an integer, but you might want to be careful for a general combination of window size and overlap.