필터 지우기
필터 지우기

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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by