NeuroPains
NeuroPains

Reputation: 1

Z-score across a whole matrix in Matlab

How would I calculate the z-score of an entire 3 dimensional matrix in Matlab?

The Matlab command zscore standardises across vectors in just one of the dimensions of multidimensional arrays.

zscore documentation: https://uk.mathworks.com/help/stats/zscore.html

Upvotes: 0

Views: 3044

Answers (1)

Wolfie
Wolfie

Reputation: 30155

Here I show two equivalent methods:

  1. You can edit zscore to view how the function works, or the documentation linked in your question gives the equation for zscore:

    zscore

    We can calculate this manually using the mean and std (standard deviation).

    M = rand( 3, 5 ) * 10
    >> M =
       9.5929       1.4929       2.5428       9.2926       2.5108
       5.4722       2.5751       8.1428       3.4998       6.1604
       1.3862       8.4072       2.4352        1.966       4.7329
    
    Z = ( M - mean(M(:)) ) / std(M(:)) % using M(:) to operate on the array as a vector
    >> Z =
       1.6598      -1.0771     -0.72235       1.5583     -0.73316
      0.26743     -0.71145       1.1698     -0.39899          0.5
      -1.1131       1.2591      -0.7587     -0.91727     0.017644   
    

    The advantage of this method is that you don't have to use the statistics toolbox required by zscore. This minor disadvantage is you lose the input checking of zscore, and protections if the standard deviation is 0.

  2. If you want to use zscore then you can use reshape, after calculating the zscore as if it were a vector:

    Z = reshape( zscore(M(:)), size(M) )
    >> Z =
       1.6598      -1.0771     -0.72235       1.5583     -0.73316    
      0.26743     -0.71145       1.1698     -0.39899          0.5
      -1.1131       1.2591      -0.7587     -0.91727     0.017644   
    

Note that both of these methods should behave the same as the standard zscore(M) for a vector input M.

Upvotes: 3

Related Questions