Contents
IS A GIVEN SQUARE MATRIX A DIAGONAL MATRIX?
Language : Matlab 2007a Authors : Autar Kaw Last Revised : November 15, 2008 Abstract: This program shows you three ways of finding out if a square matrix is a diagonal matrix. A square matrix is diagonal if all the off-diagonal elements are zero, that is A(i,j)=0 for i~=j.
clc clear all disp('This program shows you three ways of finding out') disp('if a square matrix is a diagonal matrix.') disp('A square matrix is diagonal if all the off-diagonal') disp('elements are zero, that is A(i,j)=0 for i~=j.') disp(' ')
This program shows you three ways of finding out if a square matrix is a diagonal matrix. A square matrix is diagonal if all the off-diagonal elements are zero, that is A(i,j)=0 for i~=j.
INPUTS
The square matrix
A=[1 0 0 0;0 3.4 0 0; 0 0 -4.5 0;0 0 0 0]; disp ('INPUTS') disp('Here is the square matrix') A disp(' ')
INPUTS Here is the square matrix A = 1.0000 0 0 0 0 3.4000 0 0 0 0 -4.5000 0 0 0 0 0
FIRST SOLUTION
This is based on counting the number of zeros on off the diagonal. If this count is n^2-n then it is a diagonal matrix, otherwise it is not a diagonal matrix
%size gives how many rows and columns in the A matrix rowcol=size(A); n=rowcol(1); % count = how many zeros not on the diagonal count=0; for i=1:1:n for j=1:1:n if A(i,j)==0 & i~=j count=count+1; end end end disp('FIRST WAY') if count==n^2-n disp('Matrix is diagonal') else disp('Matrix is NOT diagonal') end
FIRST WAY Matrix is diagonal
SECOND SOLUTION
This is based on finding if any of the off-diagonal elements are nozero. As soon as this condition is met, the matrix can be deemed not diagonal. If the condition is never met, the matrix is diagonal
%size gives how many rows and columns in the A matrix rowcol=size(A); n=rowcol(1); % flag = keeps track if it is diagonal or not % flag = 1 if matrix is diagonal % flag = 2 if matrix is not diagonal % Assuming matrix is diagonal flag=1; for i=1:1:n for j=1:1:n % flag=2 if off-diagonal element is nonzero. if A(i,j)~=0 & i~=j flag=2; end end end disp(' ') disp('SECOND WAY') if flag==1 disp('Matrix is diagonal') else disp('Matrix is NOT diagonal') end
SECOND WAY Matrix is diagonal
THIRD SOLUTION
This is based on finding if the sum of the absolute value of the off-diagonal elements is nonzero. If the sum is nonzero, the matrix is NOT diagonal. If the sum is zero, the matrix is diagonal
%size gives how many rows and columns in the A matrix rowcol=size(A); n=rowcol(1); % sum_off_diagonal= sum of absolute value of off-diagonal elements sum_off_diagonal=0; for i=1:1:n for j=1:1:n if i~=j sum_off_diagonal=sum_off_diagonal+abs(A(i,j)); end end end disp(' ') disp('THIRD WAY') if sum_off_diagonal==0 disp('Matrix is diagonal') else disp('Matrix is NOT diagonal') end
THIRD WAY Matrix is diagonal