Write a function in Matlab that takes as input the number n, the size of matrice
ID: 3785465 • Letter: W
Question
Write a function in Matlab that takes as input the number n, the size of matrices and vectors; m, the number of nonzero elements of a sparse matrix; and the sparse matrix whose nonzeros are given in m-component column vectors r, c, and v: the rk row, ck column entry of the matrix is nonzero with value vk, for k = 1, . . . , m. Finish the program in the following way:
(a) Have the function output the actual n × n matrix A represented. Write out or print out your function.
(b) Have the function accept also the input of x, an n-component vector, and, working directly with the r, c, and v, output the matrix-vector multiplication between the sparse matrix and the vector x, and the number of flops involved. Write out or print out your function.
(c) Assuming the sparse matrix is lower triangular and c is in non-decreasing order, have the function accept also the input of b, an n-component vector, and, working directly with the r, c, and v, output column-oriented forward substitution solving for A1 b, and the number of flops involved. Write out or print out your function.
Explanation / Answer
Part a)
function A = GenerateMatrix(n,m,r,c,v) % the function
A = zeros(n); % Creating the zero entries
for i = 1:m
A(r(i),c(i)) = v(i); % adding the nonzero entries
end
end
FUNCTION TESTING
>> n=4;
>> m=6;
>> r=[1 1 2 3 4 4];
>> c=[2 3 3 1 2 4];
>> v=[1 2 2 1 1 1];
>> A = GenerateMatrix(n,m,r,c,v)
A =
0 1 2 0
0 0 2 0
1 0 0 0
0 1 0 1
Part b)
function [A,fl] = GenerateMatrix(x,n,m,r,c,v) % the function
A = zeros(n,1); % initial value
fl = 0;
for i =1:m
A(r(i)) = A(r(i))+v(i)*x(c(i)); % computing the product
fl = fl+2; % tow operation per loop +,*
end
end
Checking the function
>> x=[1;2;3;4];
>> n=4;
>> m=6;
>> r=[1 1 2 3 4 4];
>> c=[2 3 3 1 2 4];
>> v=[1 2 2 1 1 1];
>> [A,fl] = GenerateMatrix(x,n,m,r,c,v);
>> A
A =
8
6
1
6
>> fl
fl =
12
Part C)
function [x,fl] = GenerateMatrix(b,n,m,r,c,v) % the function
A = zeros(n); % Creating the zero entries
x = zeros(n,1);% solution vector
fl =0;
for i = 1:m
A(r(i),c(i)) = v(i); % Matrix
end
for j = 1:n % column-oriented forward substitution
x(j) = b(j)/A(j,j);
b(j+1:n) = b(j+1:n) - A(j+1:n,j)*(x(j));
fl = fl + 1 + 2*(n-j-1);
end
end
Testing the function
>> b = [1;2;3;4];
>> c = [1 1 2 2 3 4];
>> r = [1 3 2 4 3 4];
>> v = [1 2 2 1 1 1];
>> n =4;
>> m =6;
>> [A,fl] = GenerateMatrix(b,n,m,r,c,v);
>> A
A =
1
1
1
3
>> fl
fl =
8
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.