HOMEWORK 1
Q1. Write a MATLAB® program to calculate the solution x for Ax=y using Gauss elimination method (with pivoting and normalization), where A is a coefficient matrix of any size.
Hints:
Use m-files to create a general function
Make use of loops and if statements as necessary
Remember
,
i.e. M=[ai,j] where i=1:3 and j=1:3.
When you define a 3-by-3 matrix in the command window, say M1, you should call the function you wrote in the m-file and the function will calculate the determinant.
Let me give you an example: The following is an m-file for a function named MySum.m that sums the elements of the matrix M
function [totalM]=SumFun(M) %the function returns totalM,
totalM=M(1,1)+M(1,2)+M(1,3)+M(2,1)+ M(2,2)+M(2,3)+M(3,1)+ M(3,2)+M(3,3) %Add the elements of the matrix
end
This code could alternatively be written as the following where M could be a matrix of any size:
function [totalM]=SumFun(M) % the function returns totalM,
[m,n]=size(M); % assigns the size of M matrix to m and n
i=1; %start at i=1
j=1; %start at j=1
totalM=0; %start at totalM=0
for i=1:m % nested loop: increment i by 1 until m
for j=1:n,
totalM=totalM+M(i,j);
end
end
totalM
To run this function, go to the command window and write a matrix
For example:
>> A=[ 1 2 3 4; 12 2 4 2; 34 3 1 6; 0 2 5 3]
>> SumFun(A) %will give you the following answer
totalM =
84
Q2. Solve the following set of equations in MATLAB® using
1. Matrix inversion
2. Gauss-Jordan relation
3. Cramer’s rule
x1 + x2 + 3 x3 = 1
x1 + 2 x2 + 5 x3 = 2
3 x1 + x2 + x3 = 1