In this lab, we will focus on matrices and directed graphs represented as adjace
ID: 3821509 • Letter: I
Question
In this lab, we will focus on matrices and directed graphs represented as adjacency matrices. It is highly recommended to use MATLAB for this lab. Roots and Leaves of a Graph Taking an adjacency matrix as input (matrix in MATLAB, 2d array in C++), return the set of roots and leaves in the graph. For example, in the graph below, the graph has roots 1, 2 and leaf 7. It is possible for a graph not to have roots and/or leaves. Determinant Write a function that takes as input a 2 times 2 matrix and a 3 times 3 matrix and outputs if the matrix is regular or singular. Implement two test cases for singular and regular.Explanation / Answer
leaf_root.m
function [ ] = rootleaf( adj )
leaf=[];
root=[];
for i=1:size(adj,2)
flag=0;
for j=1:size(adj,1)
if(adj(j,i)==1)
flag=1;
end
end
if(flag==0)
root=[root i];
end
end
for i=1:size(adj,1)
flag=0;
for j=1:size(adj,2)
if(adj(i,j)==1)
flag=1;
end
end
if(flag==0)
leaf=[leaf i];
end
end
root
leaf
end
Result:
>> adj=[0 0 1 0 0 0 0 0;0 0 1 0 0 0 0 0;0 0 0 1 1 0 0 0; 0 0 0 0 0 1 1 1;0 0 0 0 0 1 1 1;0 0 0 0 0 0 1 0;0 0 0 0 0 0 0 0;0 0 0 0 0 0 1 0;]
adj =
0 0 1 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 1 1 0 0 0
0 0 0 0 0 1 1 1
0 0 0 0 0 1 1 1
0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
>> rootleaf(adj)
root =
1 2
leaf =
7
2. Regular
function [ ] = regular( adj )
for i=1:size(adj,1)
for j=1:size(adj,2)
if(adj(i,j)==1)
adj(j,i)=1;
end
end
end
count=0;
flag=0;
for i=1:size(adj,1)
if(adj(1,i)==1)
count=count+1;
end
end
for i=2:size(adj,1)
count2=0;
for j=1:size(adj,2)
if(adj(i,j)==1)
count2=count2+1;
end
end
if(count2~=count)
flag=1;
end
end
if(flag==0)
disp('Matrix is regular');
else
disp('Matrix is not regular');
end
end
Result:
>> regular(adj)
Matrix is regular
>>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.