how to convert .txt file data to a matrix form

2 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2015-3-30
编辑:Stephen23 2015-4-1
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 个评论
Stephen23
Stephen23 2015-4-22
Sure, starting a new question would be a good idea.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by