How to read a specially structured data file
33 次查看(过去 30 天)
显示 更早的评论
I have a *.5P file (file is an output from the software WAMIT, and can be read by Matlab and/or any text editor) that I want to read through Matlab. Since I cannot upload a *.5P file here in the forum, I changed it to a *.txt file and attached the sample file here.
Now, one line of this data file would include 19 columns (each separated by a tab or space). However, the specific structure of the output file "wraps" each data line to include only 15 columns, and the next 4 lines go into a new line. I'm trying the following code to read the data.
fid = fopen('test.5p');
C = cell2mat(textscan(fid, '%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f'));
fclose(fid);
But this doesn't give me the structure I want, and instead, I get something similar to the following.
How can I read these wrapped lines to be one single line?
TIA!
** EDIT: I realized that I made a mistake with the question and the actual structure of the data file is a bit more complex than what I thought and had attached here. I posted a separate question detailing that.
0 个评论
采纳的回答
Stephen23
2023-2-27
fid = fopen('test.txt','rt');
mat = fscanf(fid,'%f',[19,Inf]).';
fclose(fid);
display(mat)
更多回答(2 个)
Askic V
2023-2-27
编辑:Askic V
2023-2-27
I would also like to suggest my naive and inefficient approach:
A = dlmread('testfile5p.txt');
nr_rows = size(A,1);
A2 = zeros(ceil(size(A,1)/2),19);
for i = 1:nr_rows-1
A2(i,:) = [A(i,:), A(i+1,1:4)];
end
B = A2(1:2:end,:);
The solution with using Inf plus transponse is really mind blowing. I would never expect that.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!