Finding average at each point
显示 更早的评论
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
采纳的回答
更多回答(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 个评论
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
2014-10-9
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.
Guillaume
2014-10-8
a = randi(100, 1, 20) %for example
b = conv(a, [1/3 1/3 1/3], 'same');
%now you can adjust for the edges:
b(1) = (a(1) + a(2)) / 2;
b(end) = (b(end) + b(end-1)) / 2
>> [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 个评论
dpb
2014-10-8
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...
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!