Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Calculating the RMS of an array

  1. Mar 18, 2009 #1
    Right, this may be really simple but I am seriously struggling with it!

    I have an array of data which shows a map of Sweden (the sea is masked out so all the values over the sea are set to 0). I need to calculate the root mean square of only the values not equal to 0 in my array, but I have no idea how to do this in Matlab. I can calculate the RMS of the whole array, but it comes out far too good (due to all the zeros over the sea!).

    So if I have a 70x40 array how do I only pick out the values not equal to zero and take the RMS of them?

    Help would be much appreciated.
  2. jcsd
  3. Mar 18, 2009 #2


    User Avatar
    Science Advisor

    What you'd need to do is to first reshape your matrix into a single vector

    >> nonzeros = reshape(map, 1, prod(size(map)))

    Then, you'd need to find the zeros and delete them (you couldn't do this without reshaping because you can't have a matrix with rows and or columns that weren't all the same length).

    >> nonzeros(find(nonzeros==0))=[]

    ...And now you can take the RMS of the non-zero entries.

    EDIT: I suppose you could also just count the number of non-zero entries and divide by that number instead of the number of elements in the array. But then you're wasting cycles on determining the RMS of the zero elements.

    >> nonzero = prod(size(find(map~=0)))
    Last edited: Mar 18, 2009
  4. Mar 18, 2009 #3
    Thank you...that worked like a treat. I'm quite new to Matlab and am still struggling with even the simplest of things!

Share this great discussion with others via Reddit, Google+, Twitter, or Facebook