Matrix addition and means

4 次查看(过去 30 天)
Joseph Pauwels
Joseph Pauwels 2014-4-11
I am trying to take a matrix of any size , whether it has one row or 9, and write a function file that add the each element by its immediate neighbor then average it and replace. So if
a=[1,2,0,1]
the function would produce
ans =
1.5 1 1 .5
here is what I have so far, but for some reason it wont add the edges.
function [ b] = Avg_Num(a )
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
[r,c]=size(a);
if (r*c) == 1
b=a;
elseif r ==1
b(1,1)=(a(1,1)+a(1,2))/2;
for j= 2:(c-1)
b(1,j)=(a(1,j)+a(1,j-1)+a(1,j+1))/3;
b(1,max(j)+1)=(a(1,max(j))+a(1,max(j)+1))/2;
end
elseif r >1
b(1,1)=(a(1,1)+a(1,2)+a(2,2)+a(2,1))/4;
b(1,c)=(a(1,c)+a(1,c-1)+a(2,c)+a(2,c-1))/4;
b(r,1)=(a(r,1)+a(r-1,1)+a(r,2)+a(r-1,2))/4;
b(r,c)=(a(r,c)+a(r-1,c)+a(r-1,c-1)+a(r,c-1))/4;
for i=2 :(r-1)
for j=2:(c-1)
b(i,j)=(a(i,j)+a(i+1,j)+a(i-1,j)+a(i,j+1)+a(i,j-1)+a(i-1,j-1)+a(i-1,j+1)+a(i+1,j-1)+a(i+1,j+1))/9;
end
end
end
end
any ideas

回答(1 个)

Image Analyst
Image Analyst 2014-4-11
编辑:Image Analyst 2014-4-11
Wow. How would you like to do all that in a single line? If so, how about using convolution:
% First with a 1D "a"
a=[1,2,0,1];
output = conv2(a, [1, 1]/2, 'same')
% Now with a 2D "a" - use a 3 by 3 array to do the scanning.
windowSize = 3
a = magic(windowSize); % Sample data
output = conv2(a, [windowSize, windowSize]/windowSize^2, 'same')
  12 个评论
Joseph Pauwels
Joseph Pauwels 2014-4-12
thats amazing, and it works on any size vector. my hat goes off to you.
Thanks for your help
Image Analyst
Image Analyst 2014-4-12
You're welcome. Can you mark the answer as "Accepted" then?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by