(This is a simplified version of Exercise 6 on page 162 of the book) Write a MAT
ID: 2264828 • Letter: #
Question
(This is a simplified version of Exercise 6 on page 162 of the book) Write a MATLAB function that receives a square matrix A as input, reduces A to row echelon form and returns the new matrix A matrix is in row echelon form if 1. all nonzero rows (rows with at least one nonzero element) are above any rows of all zeroes (all zero rows, if any, belong at the bottom of the matrix), and 2. the leading coefficient (the first nonzero number from the left, also called the pivot) of a nonzero row is always strictly to the right of the leading coefficient of the row above it. Watch this video: https://www.youtube.com/watch?v=kQMShQllPuM You have to use the colon operator. See textbook page 132 line 2. An example: >> x-rand (4,4) 0.7094 0.7547 0.2760 0.6797 0.6551 0.1626 0.1190 0.4984 0.9597 0.3404 0.5853 0.2238 0.7513 0.2551 0.5060 0.6991 >> row_echelon(x) ans = 0.7094 0.6551 0.5343 0.9597 0.6807 0.3849 0.7513 0.5442 0.3520 0.5966Explanation / Answer
Function named row_echelon
%%MATLAB function code starts
function A = row_echelon(x)
%% Introduction to the Function
% Script for Row-Echelon Form
% Definition and Use of this function
%
% row_echelon(x)
%
% x is nxn matrix
% Example
% >> a = rand(4,4);
% >> A = row_echelon(x);
% A will be a matrix in the row echelon form
%% The Code
% Check that the matrix input is a square matrix
if size(x,1) ~= size(x,2)
error('You have entered a non-square matrix. Function terminated because of error')
end
% operations to reduce the matrix to row echelon form
for i = 1:1:size(x,1) - 1 % move across all the rows which will be used to reduce other rows
for j = i+1:1:size(x,1) % move across rows starting 1 after the previous row
x(j,:) = x(j,:) - x(j,i)/x(i,i)*x(i,:); % reduce all the elements below the pivot to zero
end % j end
end % i end
A = x;
end
%%MATLAB function code ends
A typical example:
>> x = randi(4,4)
x =
2 4 3 1
4 4 1 4
3 3 2 1
2 3 2 1
>> A = row_echelon(x)
A =
2.0000 4.0000 3.0000 1.0000
0 -4.0000 -5.0000 2.0000
0 0 1.2500 -2.0000
0 0 0 -0.1000
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.