m 4. Create a function called matmanip that will receive as input argument a mat
ID: 3838386 • Letter: M
Question
m 4. Create a function called matmanip that will receive as input argument a matrix of integers, and will return as output a matrix of equal dimensions, modified in such a way that the value in each of its elements equals to the sum of the values stored in the corresponding nearest neighbor elements of the input matrix. For example, for the input matrix given on the left, the output matrix should have values as shown on the right input matrix output matrix 1 3 0 2 8 9 14 10 7 13 13 14 15 7 0 5 3 1 4 3 1 12 20 14 18 10 4 2 1 1 4 8 16 11 19 10 20 3 2 5 6 12 6 14 7 2 2 4 2 0 2 To test your function, create the 5x5 matrix mat [13 0 2 2; 0 53 1 4; 3 1 202; 4 2 1 1 4; 2 0 3 2 5, and then print to screen the output matrix returned by the call matmanip(mat) using MATLAB function disp.Explanation / Answer
function outmat = matmanip(mat)
outmat = mat;
[rows cols] = size(mat);
for i = 1:rows
for j = 1:cols
sum = 0;
for x = i-1:i+1
for y = j-1:j+1
if x > 0 && y > 0 && x <= rows && y <= cols && ~(x == i && y == j) %this checks that x and y does not cross the boundary of matrix and x and y are not equivalent to i and j, i.e. it calculates onnly the valid neighbours and not itself
sum = sum + mat(x, y);
end %end of if
end %end of y loop
end %end of x loop
outmat(i, j) = sum;
end %end of j
end %end of i
end %end of function
This function will do the job! Let me know if you have any query on the working principle of the code.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.