Here is Part-II
Importing data from a text file in matrix form
2 次查看(过去 30 天)
显示 更早的评论
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
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
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
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...
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 String Parsing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!