For this assignment, the function will take in a matrix of unknown size. Write a
ID: 3857038 • Letter: F
Question
For this assignment, the function will take in a matrix of unknown size. Write a function that returns false(0) if any edge value is a zero. Otherwise, return a matrix or size equal to the original matrix that has a zero for any non-zero position or the largest number that is adjacent (in contact) to a zero.
Example:
Instructions: To solve this problem, modify the template bellow with your code. Leave the names of the function and variables unchanged. Also maintain the names of the sub-functions. Otherwise your code will not pass the test. (In MatLab)
Explanation / Answer
The Matlab code
function matout = nearZero(matin)
[C,R] = size(matin); % getting the size of the matix
% Checking any zeros in the edge
for k = 1:R
if(matin(1,k) == 0 || matin(C,k) == 0)
matout = false(0);
return
end
end
for k = 1:C
if(matin(k,1) == 0 || matin(k,R) == 0)
matout = false(0);
return
end
end
% If there is no zero
matout = zeros(C,R); % Create a matrix ofclc zeros
I = find(matin == 0); % Get the index of zeros in the matin
% Replace the zeros in the Index I with max adjacent number
matout(I) = max([matin(I+1);matin(I-1);matin(I+R);matin(I-R)]);
end
Checking the code
>> A = [1,2,0,4;4,0,6,3;1,3,0,4;8,2,5,3]
A =
1 2 0 4
4 0 6 3
1 3 0 4
8 2 5 3
>> nearZero(A)
ans =
[]
>> A = [1,2,3,4;4,0,6,3;1,3,0,4;8,2,5,3]
A =
1 2 3 4
4 0 6 3
1 3 0 4
8 2 5 3
>> nearZero(A)
ans =
0 0 0 0
0 6 0 0
0 0 6 0
0 0 0 0
>>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.