Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way of finding average difference between elements in array

Tags:

matlab

Hope title isn't confusing. It's simple to show by example. I have a row vector like so: [1 5 6]. I want to find the average difference between each element. The differences in this example are 4 and 1 so the average is 2.5. This is a small example. My row vectors might be very large. I'm new to MatLab so is there some efficient way of using MATLAB's efficient matrix/array manipulation to do this nicely?

There is a similar question on SOF already but this question is specifically for MATLAB!

Thanks :)

EDIT: As queried by @gnovice, I wanted the absolute difference.

like image 824
ale Avatar asked Mar 01 '11 20:03

ale


2 Answers

Simple solution using diff and mean

aveDiff = mean(diff(myVector))     %#(1)

Example

>> v=[1 5 6]
v =
     1     5     6
>> mean(diff(v))
ans =
    2.5000

This works but @Jonas' answer is the correct solution.


Edit

From @gnovice, @vivid-colours and @sevenless comments.

The mean of the absolute value of the difference can be found by inserting abs into (1)

aveDiff = mean(abs(diff(myVector)))     %#(2)
like image 51
Azim J Avatar answered Nov 07 '22 09:11

Azim J


If you have an array array, then the average difference is

(array(end) - array(1))/(length(array)-1)

because diff(array), where array = [a b c d], is [b-a c-b d-c]. The average of that is (b-a+c-b+d-c)/3, which simplifies to (d-a)/3.

In your example

array = [1 5 6];

(array(end)-array(1))/2 

ans =
2.5
like image 24
Jonas Avatar answered Nov 07 '22 09:11

Jonas