Here is Part-II
Importing data from a text file in matrix form
3 views (last 30 days)
Show older comments
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 Comments
Guillaume
on 22 Apr 2015
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
on 22 Apr 2015
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...
Accepted Answer
Stephen23
on 22 Apr 2015
Edited: Stephen23
on 22 Apr 2015
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...
More Answers (0)
See Also
Categories
Find more on Text Data Preparation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!