function [b] = Avg_nbd (a) ............. end in which every element of \'b\' is
ID: 3554336 • Letter: F
Question
function [b] = Avg_nbd (a)
.............
end
in which every element of 'b' is the average of every element of 'a' and its immediate neighbors. For example, the function should work as follow:
>> Avg_nbd ( [2] )
ans =
2
>> Avg_nbd ( [1,1,1] )
ans =
1 1 1
>> a = [0, 1, 1, 1, 0];
>> Avg_nbd ( a )
ans =
0.5000 0.6667 1.0000 0.6667 0.5000
2. Now, generalize your function Avg_nbd s0 that input 'A' is any 3 x n matrix. For example:
>> A = [1; 1; 1];
>> Avg_nbd ( A )
ans =
1
1
1
>> A = [1, 0; 1, 2; 1, 0];
>> Avg_nbd ( A )
ans =
1.0000 1.0000
0.8333 0.8333
1.0000 1.0000
>> A = [1, 1, 1; 1, 2, 3; 1, 3, 6];
>> Avg_nbd ( A )
ans =
1.2500 1.5000 1.7500
1.5000 2.1111 2.6667
1.7500 2.6667 3.5000
3. Now, generalize your code so that input 'A' is any n x n matrix. For example:
>> A
A =
1 1 1 1 1
1 2 3 1 1
1 3 6 1 1
8 1 6 2 2
3 5 7 2 2
4 9 2 2 2
>>Avg_nbd ( A )
ans =
1.2500 1.5000 1.5000 1.3333 1.0000
1.5000 2.1111 2.1111 1.7778 1.0000
2.6667 3.4444 2.7778 2.5556 1.3333
3.5000 4.4444 3.6667 3.2222 1.6667
5.0000 5.0000 4.0000 3.0000 2.0000
5.2500 5.0000 4.5000 2.8333 2.0000
Please provide the complete MATLAB code! Make sure to taste with all these example! You can provide only one code that can be used with all 3 different type mentioned above.
Explanation / Answer
CODE:
%%
function [B] = Avg_nbd(A)
[r c] = size(A);
B = zeros(r,c);
for i = 1:r
for j = 1:c
value = [];
a = unique([i min(i+1,r) max(i-1,1)]);
b = unique([j min(j+1,c) max(j-1,1)]);
for k = 1:numel(a)
value = [value A(a(k),perms(b))];
end
B(i,j) = mean([value]);
end
end
%%
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.