Matrix addition and means

5 ビュー (過去 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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by