MATLAB HELP Programming 1 Write a function in Matlab that t

MATLAB HELP!

• Programming: 1. Write a function in Matlab that takes as input the number n, an n × n upper triangular matrix G, and an n-component column vector b, and returns as output the solution of G~y = ~b, using back substitution, and the number of flops used. Use only programming basics.

(a) Write out or print out your program.

(b) Create cases of your choice with n = 100, 200, 400 to run your function. Write down the number of flops used in each case.

(c) What lines in the program can you change if G were lower triangular instead of upper triangular?

Solution

Matlab function SolveSystem.m

function [Y,FLOPS] = SolveSystem(n,G,b) % function to solve Gy = b
   FLOPS = 0; % initially no operations
      for i=n:-1:1 % starting from G(n,n)
       j=i+1;
       sum=0;
       while(j<=n) % While loop to sum the computed values
           sum=sum+G(i,j)*Y(j);
           j=j+1;
           FLOPS = FLOPS+2; % Two floating point operations in this loop +,*
       end
       Y(i)=(b(i)-sum)/G(i,i); % computing the unknown
        FLOPS = FLOPS+2; % Two floating point operations -,/
      end
end


Testing the code

>> n = 5;
>> x = ones(5,1);
>> G = triu(rand(5));
>> b = G*x;
>> [Y,FLOPS] = SolveSystem(n,G,b);
>> Y

Y =

    1.0000    1.0000    1.0000    1.0000    1.0000

>> FLOPS

FLOPS =

    30

Part b)

n = [100 200 400];
for k =1:3
    x = ones(n(k),1);
    G = triu(rand(n(k)));
    b = G*x;
    [Y,FLOPS] = SolveSystem(n(k),G,b);
    fprintf(\'n=%d flops=%d\ \',n(k),FLOPS);
end

OUTPUT

>> testingSystemSolve
n=100 flops=10100
n=200 flops=40200
n=400 flops=160400

Program for Lower triangular matrix

function [Y,FLOPS] = SolveSystem(n,G,b) % function to solve Gy = b
   FLOPS = 0; % initially no operations
      for i=1:n % Changed
       j=i-1; % Changed
       sum=0;
       while(j>0) % Changed
           sum=sum+G(i,j)*Y(j);
           j=j+1;
           FLOPS = FLOPS+2; % Two floating point operations in this loop +,*
       end
       Y(i)=(b(i)-sum)/G(i,i); % computing the unknown
        FLOPS = FLOPS+2; % Two floating point operations -,/
      end
end

MATLAB HELP! • Programming: 1. Write a function in Matlab that takes as input the number n, an n × n upper triangular matrix G, and an n-component column vector
MATLAB HELP! • Programming: 1. Write a function in Matlab that takes as input the number n, an n × n upper triangular matrix G, and an n-component column vector

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site