A question regarding matrices
Mostra commenti meno recenti
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 Commenti
Sean de Wolski
il 16 Ott 2013
Could you provide the expected results for the file above?
jana
il 16 Ott 2013
Jos (10584)
il 16 Ott 2013
Modificato: Jos (10584)
il 16 Ott 2013
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
il 16 Ott 2013
Risposta accettata
Più risposte (2)
Vivek Selvam
il 16 Ott 2013
Modificato: Vivek Selvam
il 16 Ott 2013
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!
Categorie
Scopri di più su Matrix Indexing in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!