필터 지우기
필터 지우기

Importing data from a text file in matrix form

조회 수: 1 (최근 30일)
Kamal Bera
Kamal Bera 2015년 4월 22일
댓글: Stephen23 2015년 4월 23일
I have a text file (extracted from ANSYS as stiffness matrix)from which I want to obtain a 1710x1710 matrix.Since the text file large,I am attaching it in two parts(as zip files:part-I and part-II).Just copy the second part and paste at the end of first part.Here is part-I.
  • The answer should not only work for 1710x1710 case but for all sizes * ( obviously the text format will remain the same )*
  댓글 수: 5
Guillaume
Guillaume 2015년 4월 22일
Your text file is basically consisting of fixed width columns. This is a bit more difficult to parse in matlab since there's no built-in function for that. You can either read each line and split them at constant columns or use a regular expression as per Stephen's answer.
Stephen23
Stephen23 2015년 4월 22일
While regexp is used in my answer, actually a cunning use of sscanf splits that adjacent data. It relies on the fact that it there is either a space or a minus sign...

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2015년 4월 22일
편집: Stephen23 2015년 4월 22일
This requires just one small change to the solution to your last question (where the file has the same format):
str = fileread('STIFFNESS MATRIX.txt');
[tok,idx] = regexp(str, 'ROW\s*(\d+)\s+NODE\s*(\d+)\s+[^\n=]+=\s+(\w+)', 'tokens', 'end');
tok = vertcat(tok{:});
idx = [1+idx,numel(str)];
fun = @(b,e)reshape(sscanf(str(b:e),'%f'),2,[]).';
mat = arrayfun(fun, idx(1:end-1), idx(2:end), 'UniformOutput',false);
fun = @(r,v)[sscanf(r,'%i')*ones(size(v,1),1),v];
mat = cellfun(fun, tok(:,1), mat(:), 'UniformOutput',false);
mat = vertcat(mat{:});
out = zeros(size(tok,1));
ind = sub2ind(size(out),mat(:,1),mat(:,2));
out(ind) = mat(:,3);
The only change that I made was to change the regexp token-substring from \s+ to \s*, to allow for the ROW value to occur right next to the ROW text, with or without any space characters. Everything else works just as it did before. The output is too large to be shown, but here are the first and last eight values:
>> out(1,1:8)
ans =
1.0e+10 *
0.3212 -4.0406 -0.0000 0.0000 -0.0000 -0.0556 -0.1616 3.2060
>> out(end,end-7:end)
ans =
1.0e+13 *
0 0 0.0571 0.0000 -0.0000 0.0000 0.0000 1.0209
which matches the values in the text file. You can check the other 2924084 values somehow...
  댓글 수: 2
Kamal Bera
Kamal Bera 2015년 4월 23일
It is working.Although I have not checked for other matrix dimensions, hope it would work.Again sorry for any inconvenience caused by me and thank you for your kind consideration. I am accepting your answer.
Stephen23
Stephen23 2015년 4월 23일
I'm glad to help!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by