Effacer les filtres
Effacer les filtres

how to convert .txt file data to a matrix form

2 vues (au cours des 30 derniers jours)
Kamal Bera
Kamal Bera le 30 Mar 2015
Commenté : Kamal Bera le 22 Avr 2015
I have a text file 'MatK.txt'(extracted from ANSYS as stiffness matrix) which has data as follows:
MATK:
[1,1]: 2.250e+007 [1,3]:-1.688e+007 [1,4]: 1.125e+007
[2,2]: 1.500e+009 [2,5]:-7.500e+008
[3,3]: 3.375e+007 [3,6]: 1.688e+007
[4,4]: 4.500e+007 [4,6]: 1.125e+007
[5,5]: 7.500e+008
[6,6]: 2.250e+007
in which the value inside [ , ] represents row and column number. since it is a symmetric matrix it only shows the upper triangular part. I want the full 6x6 matrix.
Kindly help me out. Thanks in advance

Réponse acceptée

Stephen23
Stephen23 le 30 Mar 2015
Modifié(e) : Stephen23 le 1 Avr 2015
It is not clear exactly what your question is: are you having difficulty reading this data from the file, or converting the text data into a matrix, or filling the matrix from the upper triangle data given? Below is some code that should cover most of these topics. First we define the given data as a string (is this how you read it from the file?):
>> str = 'MATK: [1,1]: 2.250e+007 [1,3]:-1.688e+007 [1,4]: 1.125e+007 [2,2]: 1.500e+009 [2,5]:-7.500e+008 [3,3]: 3.375e+007 [3,6]: 1.688e+007 [4,4]: 4.500e+007 [4,6]: 1.125e+007 [5,5]: 7.500e+008 [6,6]: 2.250e+007';
Now we can extract all of the numeric data using regexp: Edited to parse the negative values:
>> tok = regexp(str,'\[(\d),(\d)\]: ?(\S+)','tokens');
>> mat = cellfun(@(s)sscanf(s,'%f'),vertcat(tok{:}));
and then place the data in the given locations to get the upper-triangular matrix using sub2ind:
>> out = zeros(max(mat(:,1)),max(mat(:,2)));
>> ind = sub2ind(size(out),mat(:,1),mat(:,2));
>> out(ind) = mat(:,3)
out =
1.0e+009 *
0.0225 0 -0.0169 0.0113 0 0
0 1.5000 0 0 -0.7500 0
0 0 0.0338 0 0 0.0169
0 0 0 0.0450 0 0.0113
0 0 0 0 0.7500 0
0 0 0 0 0 0.0225
From which we can very easily generate the whole matrix using triu:
>> out = triu(out) + triu(out,1).'
out =
1.0e+009 *
0.0225 0 -0.0169 0.0113 0 0
0 1.5000 0 0 -0.7500 0
-0.0169 0 0.0338 0 0 0.0169
0.0113 0 0 0.0450 0 0.0113
0 -0.7500 0 0 0.7500 0
0 0 0.0169 0.0113 0 0.0225
Alternative using textscan:
>> tok = cell2mat(textscan(str(6:end),'[%f,%f]:%f'))
  30 commentaires
Stephen23
Stephen23 le 22 Avr 2015
Sure, starting a new question would be a good idea.
Kamal Bera
Kamal Bera le 22 Avr 2015
OK

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by