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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With