Text File read and write out

49 次查看(过去 30 天)
Thuan
Thuan 2017-5-24
Hey guys, I'm new to Matlab, and hoping I can get some some help. I'm trying to read in a text file and write it to the format I want. fileread('file') will give me the following data
1356297 2 0.0521214521 0.0005944170 0.0016546078 0.0125977102
4197358 89 0.0523557459 0.1244454656 -0.164303258 -0.542853886
3679865 104 0.0540524244 -0.015693102 -0.004209815 0.0009847531
I want it to write this data to the following format.
"Node 1356297", "Node 4197358", "Node 3679865"
"<0.0005944170, 0.0016546078, 0.0125977102>", @
"<0.1244454656, -0.164303258, -0.542853886>", @
"<-0.015693102, -0.004209815, 0.0009847531>", @
Thanks, Thuan
  2 个评论
Fernando Fernandes
Fernando Fernandes 2017-5-24
I think you may find your answer here:
https://www.mathworks.com/help/matlab/ref/textread.html
Walter Roberson
Walter Roberson 2017-5-24
textread is not recommended; it has been pretty much replaced by textscan or other routines.

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2017-5-24
With your regular structure and no headers, you can use load() to read the file.
data = load('file');
ids = data(:,1);
vecs = data(:,4:end);
fid = fopen('Output.txt', 'wt');
fmt = [strjoin( repmat( {'"Node %d"'}, 1, length(ids), ', '), '\n'];
fprintf(fmt, ids);
fmt = ['"<', strjoin( repmat( {'%f'}, 1, size(vecs,2) ), ','), '>" @\n'];
fprintf(fmt, vecs.'); %transpose is important
fclose(fid);
  2 个评论
Thuan
Thuan 2017-5-25
编辑:Walter Roberson 2017-5-25
How would I do it if I have a heading let say
MSC.Patran 21.1.348049 Fri Jul 03 23:12:17 PDT 2015 - Analysis Code: MSC.Nastran
Load Case: 653215
Result
1356297 2 0.0521214521 0.0005944170 0.0016546078 0.0125977102
Walter Roberson
Walter Roberson 2017-5-25
If I correctly count there as being 4 header lines, then,
fid = fopen('file', 't');
data = cell2mat( textscan(fid, '', 'HeaderLines', 4, 'CollectOutput', true) );
fclose(fid);

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by