Finding average at each point
Mostrar comentarios más antiguos
I have a data say: 1 2 3 4 5 6 7 8
(8x1 vector). I want to find the average of each number using the 2 other numbers(one below and one above) and divide by 3. And for the first and the last numbers the average will be done by taking the average of the number with next below and the one above respectively and divide by 2. I want to write a script that can do this for this data and can also be used for large data (say 1000x1 vector). Thanks in advance
Respuesta aceptada
Más respuestas (3)
>> A = 1:8;
>> [mean(A(1:2)),conv(A,[1,1,1],'valid')/3,mean(A(end-1:end))]
The end conditions require some special handling (and is of dubious mathematical value), so the simpler solution is to only have an output where three values are averaged:
>> conv(A,[1,1,1],'valid')/3
Another advantage of this is that the length of your moving window can be adjustable (not hardcoded):
>> N = 4;
>> conv(A,ones(1,N),'valid')/N
2 comentarios
Mayowa: a convolution is like a "moving window" multiply.
You can think of it like two vectors that are aligned together at one end, the corresponding elements are multiplied, and then the vectors shifted by one position relative to each other, and the process repeats until they are aligned at the other end. Dividing the resulting products by the length of the shorter "window" vector gives you the means of the original values of the longer vector.
The end values (which you defined as special cases) are calculated separately using the simple mean function.
Mohammad Abouali
el 9 de Oct. de 2014
except that you have to note that in convolution the second vector is flipped. for symmetric vectors (like in this case) it doesn't matter but if you are using non-symmetric kernel then that matters.
The one that does not flips the kernel is the cross correlation.
>> [mean(v(1:2)) conv(v,[1 1 1]/3,'valid') mean(v(end-1:end))]
ans =
1.5000 2.0000 3.0000 4.0000 5.0000 6.0000 7.0000 7.5000
More general for N points is
a=[mean(v(1:N-1)) conv(v,ones(1,N)/N,'valid') mean(v(end-(N-1):end))];
2 comentarios
This generates an error "Error: Unexpected MATLAB expression.", pointing at that space character. An extra bracket behind after the mean is required.
Although this still misses the requirement "...for the first and the last numbers the average will be..."
dpb
el 8 de Oct. de 2014
Missed the closing parens on the mean() -- the extension for end effect ought to be self-evident altho didn't write it, granted.
Edited Answer to correct oversight and typo...
Categorías
Más información sobre Logical en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!