In the code space provided in Matlab Grader, create a function that:
1. Accepts an input matrix A as its only input argument. Matrix A is a 3x3 matrix of random integers between 1 and 4
2. Produces and output matrix B as its only output argument. Matrix B will also be a 3x3 matrix.
3. Calculates the elements of matrix B such that: a. the values of B along the diagonal are equal to the respective elements in A b. the values in each element of B not along the diagonal are equal to the sum of the values in the respective row and column of A
Use for loop.
The function is as follows
function B = matrixAB(A)
for i =1:3
for j = 1:3
if i==j
B(i,j)=A(i,j); % the values of B along the diagonal are equal to
the respective elements in A
else
B(i,j) = sum(A(i,:))+sum(A(:,j)); % the non diagonal values in B
are equal to the sum of the values in the respective
% row and column of A
end
end
end
end
To get a matrix of random integer values between 1 and 4, we can use
A = randi([1 4],3,3)
where 1 and 4 are the range, 3 and 3 is the number of rows and columns of the matrix required
To check the function, first generate the matrix using the command
A = randi([1 4],3,3)
Now call the function
B = matrixAB(A)
Example Output
>> A = randi([1 4],3,3)
A =
3 3 1
4 3 2
2 1 4
>> B = matrixAB(A)
B =
3 14 14
18 3 16
16 14 4
>>
Get Answers For Free
Most questions answered within 1 hours.