フィルターのクリア

how to convert .txt file data to a matrix form

2 ビュー (過去 30 日間)
Kamal Bera
Kamal Bera 2015 年 3 月 30 日
コメント済み: Kamal Bera 2015 年 4 月 22 日
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.
Kamal Bera
Kamal Bera 2015 年 4 月 22 日
OK

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by