Exercise 1: Write MATLAB code to create a 5x5 matrix A with 2's
on the diagonal, and -1 on the super- and sub-diagonal. Then
replace the (1,1) element of A with a 1.
(Make your commands capable of handling an arbitary sized NxN
matrix by first defining N=5, then using the variable N as the size
in each of the commands.)
MATLAB Code:
close all
clear
clc
N = 3;
A = make_matrix(N);
disp('A (N = 3) ='), disp(A)
N = 5;
A = make_matrix(N);
disp('A (N = 5) ='), disp(A)
N = 7;
A = make_matrix(N);
disp('A (N = 7) ='), disp(A)
function A = make_matrix(N)
A = diag(2*ones(N,1));
for i = 1:1:N
for j = 1:1:N
if j == i + 1
A(i,j) = -1;
elseif i == j + 1
A(i,j) = -1;
end
end
end
A(1,1) = 1;
end
Output:
A (N = 3) =
1 -1 0
-1 2 -1
0 -1 2
A (N = 5) =
1 -1 0 0 0
-1 2 -1 0 0
0 -1 2 -1 0
0 0 -1 2 -1
0 0 0 -1 2
A (N = 7) =
1 -1 0 0 0 0 0
-1 2 -1 0 0 0 0
0 -1 2 -1 0 0 0
0 0 -1 2 -1 0 0
0 0 0 -1 2 -1 0
0 0 0 0 -1 2 -1
0 0 0 0 0 -1 2
Get Answers For Free
Most questions answered within 1 hours.