Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(a) Write MATLAB code to create an array A of size 5 x 5. The values of the arra

ID: 2085810 • Letter: #

Question

(a) Write MATLAB code to create an array A of size 5 x 5. The values of the array should be integers between 0 and 20.

(b) Using only one line of code, replace the whole first column of A with the value 5. Save the result in array B.

(c) Using only one line of code, replace the whole 3 x 3 block of array B consisting of rows 3 to 5 and columns 3 to 5 with the value 0. This block is B(3:5,3:5). Save the result in array C.

(d) Write code to switch the 2 x 2 block of array C consisting of rows 4 to 5 and columns 1 and 2, with the block of array C consisting of rows 1 and 2 and columns 4 and 5. Save the result in array D.

(e) Write one line of code which performs the element-wise multiplication of arrays A and B, and add C to the result.

(f) Write one line of code to compute an array which contains the square values of all elements in A.

(g) Write one line of code to divide all elements of A by the corresponding elements of B, and subtract C from the result. Do you see any "inf" or "nan" values in the result? What do they mean?

Explanation / Answer

MATLAB code is given below followed by the results.

A = randi(20,5,5); % create Matrix A
A(:,1) = 5; % Define first column of A 5
B = A; % Define B from A
B(3:5,3:5) = 0; % Make zeros in B
C = B; % Define C from B
M = C(1:2,4:5);
N = C(4:5,1:2);
C(4:5,1:2) = M; % swap elements of C
C(1:2,4:5) = N; % swap elements of C
D = C; % define D
P = A.*B+C; % element wise multiply A &B then add to C
Q = A.^2; %element wise square
R = C - A./B; % divide Each element of A by B and subtract from C

Results:

R

R =

4 17 12 4 2
4 11 7 4 17
4 10 -Inf -Inf -Inf
4 0 -Inf -Inf -Inf
2 18 -Inf -Inf -Inf

It is observed from the martix R (C - elementwise A / B) that the 3x3 block (rows 3 to 5 and columns 3 to 5) is "inf"

this is because of the fact that the matrix B is zeros in the field where R is infinite. when you divide any integer value by zero you get infinity.

Here A and B are as given below.

>> A

A =

5 18 13 5 1
5 12 8 3 19
5 11 11 4 19
5 3 9 5 10
5 18 2 9 10

>> B

B =

5 18 13 5 1
5 12 8 3 19
5 11 0 0 0
5 3 0 0 0
5 18 0 0 0