A question regarding matrices
이전 댓글 표시
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.
댓글 수: 4
Sean de Wolski
2013년 10월 16일
Could you provide the expected results for the file above?
jana
2013년 10월 16일
Jos (10584)
2013년 10월 16일
편집: Jos (10584)
2013년 10월 16일
There are some inconsistencies in your question and comment:
- Does "E 1 2 10" mean that G(1,2) will be 10 but also that G(2,1) should be 10?
- And do you want it to be 0 or -1 when there is no edge?
jana
2013년 10월 16일
채택된 답변
추가 답변 (2개)
Vivek Selvam
2013년 10월 16일
편집: Vivek Selvam
2013년 10월 16일
Using dlmread():
function G = adjacencyMatrix()
filename = 'myFile.txt';
delimiterIn = ' ';
startRow = 1;
startCol = 1;
M = dlmread(filename,delimiterIn,startRow,startCol);
numNodes = M(1,1);
G = -1*ones(numNodes);
node1 = M(3:end,1);
node2 = M(3:end,2);
cost = M(3:end,3);
for k = 1:numel(node1)
G(node1(k),node2(k)) = cost(k);
G(node2(k),node1(k)) = cost(k);
end
end
Here's another option using TEXTSCAN. Note also the illustration of SPARSE and FULL at the end of the code. The main difficulty here may be to understand how to use cell arrays in MATLAB. You can find more information here: Cell arrays doc. At the very end, I also use logical indexing: Logical indexing doc page
% Open file
fileID = fopen('adjMat.txt');
% Read number of nodes and edges
H = textscan(fileID, '%s %f', 2, 'HeaderLines', 1);
disp(['Number of ' H{1}{1} ':'])
NumberOfNodes = H{2}(1)
disp(['Number of ' H{1}{2} ':'])
NumberOfEdges = H{2}(2)
% Read all remaining lines ("E x x x" lines)
C = textscan(fileID, '%c %f %f %f');
ArrayOfInitialNodes = C{2}'
ArrayOfFinalNodes = C{3}'
ArrayOfEdgeWeights = C{4}'
% Close file
fclose(fileID);
% Create adjacency matrix in sparse format with zeros instead of -1
% (memory efficient if there are lots of zeros)
AdjMatrixSparseWithZeros = ...
sparse(ArrayOfInitialNodes, ArrayOfFinalNodes, ArrayOfEdgeWeights, ...
NumberOfNodes, NumberOfNodes);
AdjMatrixSparseWithZeros = ...
AdjMatrixSparseWithZeros + AdjMatrixSparseWithZeros'
% Transform it to full format (no compact storage in memory)
% and replace zeros with -1
AdjMatrixFullWithNegOnes = full(AdjMatrixSparseWithZeros);
AdjMatrixFullWithNegOnes(AdjMatrixFullWithNegOnes==0) = -1
Hope this helps provide yet another perspective!
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!