Find the average between values in a matrix
5 views (last 30 days)
Show older comments
Suppose im given a 1 X n matrix called a and i want to find matrix b which will give the average value of every element of a and its immediate neighbors
for example. a=[0 2 1 1 0].
b=[1 1 1.3 0.667];
Whats a smart way to do this?
0 Comments
Accepted Answer
Star Strider
on 13 Apr 2014
Edited: Star Strider
on 13 Apr 2014
I suggest:
a = [0 2 1 1 0];
for k1 = 1:length(a)-1
ix1 = max(1,(k1-1));
ix2 = min(length(a),k1+1);
m(k1) = mean(a(ix1:ix2));
end
produces:
m =
1.0000 1.0000 1.3333 666.6667
3 Comments
Star Strider
on 13 Apr 2014
My pleasure!
The (k1-1) originated in my initial desire to not get an index-out-of-bounds error. Then I thought of creating the ix1 and ix2 variables and forgot to reset the k1 limit in the for statement. My error.
An -1 index, and an index >length(a) would both throw errors, since neither exists. In order to include [a(1) a(2)] as the first and [a(end-1) a(end)] as the last sub-arrays to average (the others being [a(k1-1) a(k1) a(k1+1)]), the ix1 and ix2 calculations look for the minimum or maximum of the size of the arrays and only use the indices that are within the index range of the arrays. In other words, they prevent the occurrence of indices of (-1) and (end+1). (Since you specified ‘the average value of every element of a and its immediate neighbors’ and illustrated it in your example, that eliminated a(1) alone and a(end) alone being included in the algorithm.)
More Answers (1)
Image Analyst
on 13 Apr 2014
You can try conv():
b = conv(a, [1,1,1]/3, 'full')
b = conv(a, [1,1,1]/3, 'valid')
b = conv(a, [1,1,1]/3, 'same')
Each of the shapes handles the "edge conditions" differently. It depends on what you want to do.
4 Comments
Image Analyst
on 13 Apr 2014
Edited: Image Analyst
on 13 Apr 2014
Oh my gosh. Convolution is used everywhere! It's the basis of linear systems theory and linear filtering. As just one example, if you have a sharp image and you blur it by the point spread function of the imaging system you will get an image that is the convolution of the image and the point spread function. And the whole basis of the duality of filtering in Fourier (spectral domain) and spatial (or time) domain is built upon convolution. Basically multiplication in the spatial (or time) domain is convolution in the Fourier domain, and multiplication in the spatial (or time) domain is convolution in the Fourier domain. As soon as you have your first course in linear systems, linear filtering, or optics you should get a heavy intensive education in convolution. Here's some background for you:
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!