txt file to matlab matrix form

2 visualizaciones (últimos 30 días)
Kamal Bera
Kamal Bera el 1 de Abr. de 2015
Comentada: Stephen23 el 22 de Abr. de 2015
. I have another question.If a text file (attached)in which corresponding to each row all the column values are given e.g.
ROW 1 NODE 1 DEG. OF. FR. = ROTZ
1 0.13513535E+09 2 0.00000000E+00 3 0.91507762E+08 4-0.59130175E+08
5 0.00000000E+00 6 0.00000000E+00 7 0.00000000E+00 8-0.36603105E+09
9 0.00000000E+00 10 0.00000000E+00 11 0.00000000E+00 12 0.10701035E+09
13 0.00000000E+00 14 0.00000000E+00 15 0.00000000E+00 16 0.00000000E+00
17 0.00000000E+00 18 0.00000000E+00
ROW 2 NODE 2 DEG. OF. FR. = UX
1 0.00000000E+00 2 0.35000101E+10 3 0.00000000E+00 4 0.00000000E+00
5 0.25000125E+09 6 0.00000000E+00 7-0.20000063E+10 8-0.33333439E+06
9 0.00000000E+00 10 0.00000000E+00 11 0.00000000E+00 12 0.00000000E+00
13-0.20000063E+10 14 0.33333439E+06 15 0.00000000E+00 16 0.00000000E+00
17 0.00000000E+00 18 0.00000000E+00
and so on upto 18 rows ( *Please see the attached file for clarity* ). What modification I need to do in my code to get a 18x18 matrix.
Again thank you for your quick responses. It will help me to progress further in my work

Respuesta aceptada

Stephen23
Stephen23 el 1 de Abr. de 2015
Editada: Stephen23 el 2 de Abr. de 2015
Try this. Firstly read the file into a string (note that I removed the space at the end of the filename):
str = fileread('STIFFNESS MATRIX.txt');
Then extract the data from the block headers, including the row numbers:
[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)];
Extract the data from the blocks:
fun = @(b,e)reshape(sscanf(str(b:e),'%f'),2,[]).';
mat = arrayfun(fun, idx(1:end-1), idx(2:end), 'UniformOutput',false);
Convert the data from string into numeric:
fun = @(r,v)[sscanf(r,'%i')*ones(size(v,1),1),v];
mat = cellfun(fun, tok(:,1), mat(:), 'UniformOutput',false);
mat = vertcat(mat{:});
And finally transfer the numeric data into one single numeric array, by using the row and column indices to allocate the data:
out = zeros(size(tok,1));
ind = sub2ind(size(out),mat(:,1),mat(:,2));
out(ind) = mat(:,3)
This gives one matrix containing the complete data:
>> out
out =
1.0e+09 *
Columns 1 through 14
0.1351 0 0.0915 -0.0591 0 0 0 -0.3660 0 0 0 ...
Columns 15 through 18
0 0 0 0
0 0 0 0
...
0 0 0 0
0 0 0 0
1.4636 -0.0000 0 0
-0.0000 0.0138 0.0001 0
0 0.0001 0.5012 0
0 0 0 0.5180

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by