MATLAB: A question regarding matrices

adjacency matrix

I have a data file that looks like this:
SECTION Graph
Nodes 10
Edges 5
E 1 2 10
E 2 4 2
E 4 3 1
E 9 10 9
E 4 10 6
E 1 2 10 means there is an edge between 1 and 2 and have a cost 10. I would like to read this data from my data file and create an adjacency matrix G using this data where the G(i,j) is the cost of edge(i,j) and it is -1 if there is no edge. Please Help, I am fairly new to matlab.

Best Answer

Hi,
Below is a working code for reading your specific file.
function adjMatrix = adjMatrix()
fileID = fopen('adjMat.txt');
tline = fgets(fileID);
count = 1;
nodes = 0;
edges = 0;
adjMatrix = [];
while(ischar(tline))
count = count +1;
tline = fgets(fileID);
if(tline == -1)
break;
end
tline = strtrim(tline);
if(count == 2)
nodes = str2num(tline(end-1:end));
adjMatrix = zeros(nodes);
elseif(count == 3)
edges = str2num(tline(end));
else
splitStr = strsplit(tline);
node1 = str2num(splitStr{2});
node2 = str2num(splitStr{3});
cost = str2num(splitStr{4});
adjMatrix(node1,node2) = cost;
adjMatrix(node2,node1) = cost;
end
end
fclose(fileID);
adjMatrix(adjMatrix == 0) = -1;
end