MATLAB: Find the average point with the four points surround it, using For-loop and function

for loopfunction

Hi guys,
I had trouble on getting the average point with the four points surround it. Matlab said there is a error on a(i,n) = 0.2*(a(i-1,n) + a(i+1,n) + a(i,n+1) + a(i,n-1) + a(i,n)) and I can't get rid of it. Can anyone help me up with that? And also, for setting the four boundaries of the array, a, to zero, I use the zeros() function, I think I might also get wrong with that. I made some comment on it and hope it helps.
function averahepoint(k,n)
% k is the number of time steps
% n is the size of a square n x n matrix
a = peaks(n); % make an arbitrary square matrix
a = zeros(k); % Set the four boundaries of the array, a, to zero.
% It means every element in the array where the first index equals 1 or n,
% or the second index equals 1 or n must be set equal to zero.
% A loop that performs statements the number of times you entered as an input to your
% function.
for i = 1:k
a(i,n) = 0.2*(a(i-1,n) + a(i+1,n) + a(i,n+1) + a(i,n-1) + a(i,n))
% average each point in array a excluding the points on the boundaries with the four points
% that surround it
% For example a(23,60) = 0.2*(a(22,60) + a(24,60) + a(23,61) + a(23,69) + a(23,60))
disp(i)
if mod(i,10)==0 % Every 10 iterations ,make a filled contour plot of the array
disp('Hello')
end
end
end

Best Answer

Try using two loops (one over rows and one over columns), and have a separate matrix for the output called averagedMatrix, which you will then return:
function averagedMatrix = averagepoint(k,n)
% k is the number of time steps
% n is the size of a square n x n matrix
a = peaks(n); % make an arbitrary square matrix
averagedMatrix = zeros(k); % Set the four boundaries of the array, a, to zero.
% It means every element in the array where the first index equals 1 or n,
% or the second index equals 1 or n must be set equal to zero.
% A loop that performs statements the number of times you entered as an input to your function.
[rows, columns] = size(a);
for col = 2 : columns - 1
for row = 2 : rows - 1
averagedMatrix(row, col) = 0.2 * (a(row-1, col-1) + ......
Related Question