Question: Write a function file, M = TriDiagonalMatrix ( n ) , that takes input arguments of an integer n and returns a square matrix of

Write a function file, M = TriDiagonalMatrix (n), that takes input arguments of an integer n and
returns a square matrix of size n where the first and last rows are zeros and the middle rows (2,3,..,n-1) are constructed according to the pattern defined in the following examples.
M = TriDiagonalMatrix(3)
M =[000;246;000]
M = TriDiagonalMatrix(5)
M =[00000; 24600;036900; 004812;00000]
M = TriDiagonalMatrix(10)
M =[0000000000;2460000000;0369000000;00481200000;000510150000;000061218000;000007142100;000000816240;000000091827; 0000000000]
Your function must perform the following
1. Pre-allocate the output parameter M to the appropriate size.
2) Use a loop to modify the values in the middle rows (2,3,..., n-1).
3. If the input parameter n is less than 3, assign M a value of NaN.
This is done in MATLAB. This is code I tried earlier but doesn't work according to the test codes I have.
function M = TriDiagonalMatrix(n)
if n <3
M = NaN;
return;
end
M = zeros(n);
for i =2:n-1
M(i, i-1)= i-1;
M(i, i)= i;
M(i, i+1)= i+1;
end
end
If possible, can you try to include the 3 by 3,5 by 5, and 10 by 10 matrices inside the code instead of the "i" notation I used?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!