Function Name: arrayReplace % Inputs (3): - (double) A MxN array % - (double) A
ID: 3648430 • Letter: F
Question
Function Name: arrayReplace% Inputs (3): - (double) A MxN array
% - (double) A MxN array
% - (double) A number
% Outputs (1): - (double) The original array with the replacements made
%
% Function Description:
% Write a function called "arrayReplace" that takes two arrays and a
% number and replaces all instances of that number in the first array
% with the corresponding positions of the second array. If the number
% does not exist in the array, it should just return the original array
% with no changes.
%
% Notes:
% - You can assume the arrays will always be the same size.
%
% Hints:
% - When you use logical indexing with an array, it returns an array of
% logicals. This is called a "mask". See how you can use this to solve
% the problem.
%
% Test Cases:
% arr1 = [7 7 7 7
% 7 4 4 7
% 7 4 4 7
% 7 7 7 7];
%
% arr2 = [8 8 8 8
% 8 1 2 8
% 8 3 4 8
% 8 8 8 8];
%
% out1 = arrayReplace(arr1, arr2, 4);
% out1 => [7 7 7 7
% 7 1 2 7
% 7 3 4 7
% 7 7 7 7]
%
% out2 = arrayReplace(arr1, arr2, 7);
% out2 => [8 8 8 8
% 8 4 4 8
% 8 4 4 8
% 8 8 8 8]
%
% out3 = arrayReplace(arr1, arr2, 6);
% out3 => [ 7 7 7 7
% 7 4 4 7
% 7 4 4 7
% 7 7 7 7]
%
Explanation / Answer
function replace=arrayReplace(a,b,num) replace=a;%copy a [row,col]=size(a); %%mask=zeros(size(a));%unnecessary complication, no mask used for i=1:row for j=1:col if (a(i,j)==num) replace(i,j)=b(i,j); % else % replace(i,j)=a(i,j); end end end
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.