Challenging Question - Finding mean of specific values of matrix and re-entering

1 Ansicht (letzte 30 Tage)
Have tried countless times but need help
Writing script which has matrix M and returns a new Matrix where each element of N is the corresponding element of M averaged with its next elements above, below and left and right.
The script must work for any sized square matrix!

Antworten (4)

Arnaud
Arnaud am 27 Aug. 2014
Fonctionne pour n'importe quel noyau K de taille 3 (facile à passer à une taille quelconque) et matrice M de taille quelconque :
M = [1 2 3; 4 5 6; 7 7 9];
K = [0 1 0;1 1 1;0 1 0];
Y = conv2(padarray(M,[1 1]),K,'same');
OK = conv2(padarray(ones(size(M)),[1 1]),K,'same');
Y = Y(2:end-1,2:end-1)./OK(2:end-1,2:end-1)

Salaheddin Hosseinzadeh
Salaheddin Hosseinzadeh am 27 Aug. 2014
Hey Karan,
Sound very easy and typical!
It's nothing but programming and defining some conditions. you need 2 for loops for 2 dimension matrix, one to check for vertical neighbors and one for horizontal neighbors.
Once you're finding the neighbors in for loops you should check not to exceed matrix x or y dimension, and also not getting below 1, there is no index 0 in matlab (C C++ has index 0)
and neighbor definition is the current index - and + 1 as you know.
Find them correctly, add them and put them in a new matrix using the current index.
Oh, BTW, to get the matrix dimension you can use size
size(M,1) or size(M,2) whichever you need!
see MATLAB documentation for size
doc size
Good Luck!

Andrei Bobrov
Andrei Bobrov am 27 Aug. 2014
Bearbeitet: Andrei Bobrov am 27 Aug. 2014
s = size(M);
l = true(s);
l(2:end-1,2:end-1) = false;
l1([1,s(1),numel(M)-[s(1)-1,0]]) = true;
l1 = reshape(l1,s);
l2 = l & ~l1;
N = conv2(M,[0 1 0;1 1 1;0 1 0]/5,'same'); % N = imfilter(M,[0 1 0;1 1 1;0 1 0]/5);
N(l1) = N(l1)*5/3;
N(l2) = N(l2)*5/4;

stalin
stalin am 27 Aug. 2014
Bearbeitet: Randy Souza am 28 Aug. 2014
clear all
A=[1 2 3 4;5 6 7 8; 9 10 11 12; 13 14 15 16]
[l m]=size(A)
for i=1:l
for j=1:m
if i==1&&j==1
B(i,j)=(A(i,j)+A(i+1,j)+A(i,j+1))/3
elseif i==1&&j==m
B(i,j)=(A(i,j)+A(i+1,j)+A(i,j-1))/3
elseif i==l&&j==1
B(i,j)=(A(i,j)+A(i-1,j)+A(i,j+1))/3
elseif i==l&&j==m
B(i,j)=(A(i,j)+A(i-1,j)+A(i,j-1))/3
elseif i==1
B(i,j)=(A(i,j)+A(i+1,j)+A(i,j-1)+A(i,j+1))/4
elseif i==l
B(i,j)=(A(i,j)+A(i,j+1)+A(i,j-1)+A(i-1,j))/4
elseif j==1
B(i,j)=(A(i,j)+A(i-1,j)+A(i+1,j)+A(i,j+1))/4
elseif j==m
B(i,j)=(A(i,j)+A(i+1,j)+A(i-1,j)+A(i,j-1))/4
else
% B(i,j)=0
B(i,j)= (A(i,j)+A(i-1,j)+A(i,j+1)+A(i+1,j)+A(i,j-1))/5
end
end
end

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by