how to convert .txt file data to a matrix form

5 views (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 30 Mar 2015
Edited: Stephen23 on 1 Apr 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 Comments
Stephen23
Stephen23 on 22 Apr 2015
Sure, starting a new question would be a good idea.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!