Matrix addition and means

조회 수: 4 (최근 30일)
Joseph Pauwels
Joseph Pauwels 2014년 4월 11일
댓글: Image Analyst 2014년 4월 12일
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
Azzi Abdelmalek
Azzi Abdelmalek 2014년 4월 11일
How did you get the result from a=[1,2,0,1] ?

댓글을 달려면 로그인하십시오.

답변 (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에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by