Effacer les filtres
Effacer les filtres

Importing data from a text file in matrix form

1 vue (au cours des 30 derniers jours)
Kamal Bera
Kamal Bera le 22 Avr 2015
Commenté : Stephen23 le 23 Avr 2015
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 commentaires
Guillaume
Guillaume le 22 Avr 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
Stephen23 le 22 Avr 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...

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 22 Avr 2015
Modifié(e) : Stephen23 le 22 Avr 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...
  2 commentaires
Kamal Bera
Kamal Bera le 23 Avr 2015
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 le 23 Avr 2015
I'm glad to help!

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by