Read a punch file
53 views (last 30 days)
Show older comments
Hi everyone,
I need to read a punch file (.pch). And then I have to create a matrix from the values contained in this file.
I am having some problem on reading this file on Matlab.
Here you can find attached a screenshot from the file. (the .pch file is to large to attach)
So I basically want to get the first coloumn of integers (10,11.........) and the six floatings with a for cycle but I don't know how to read the file.
I would be glad if anyone helps me. Thank you in advance.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1129300/image.png)
4 Comments
Answers (1)
Voss
on 19 Sep 2022
This may work:
% read the file contents as a char vector:
fid = fopen('sample.txt'); % (had to change extension to txt to upload)
str = char(fread(fid).');
fclose(fid);
% split into a cell array of char vectors, one cell per line:
lines = strtrim(split(str,newline()));
% remove lines starting with '$':
lines(startsWith(lines,'$')) = [];
% coombine -CONT- lines with the previous non--CONT- line:
is_start_line = ~startsWith(lines,'-CONT-');
idx = cumsum(is_start_line);
new_lines = cell(idx(end),1);
for ii = 1:numel(lines)
if is_start_line(ii)
new_lines{idx(ii)} = lines{ii};
else
new_lines{idx(ii)} = [new_lines{idx(ii)} lines{ii}(7:end)];
end
end
% sscanf each line to get the numbers out:
data = zeros(numel(new_lines),8);
for ii = 1:numel(new_lines)
data(ii,:) = sscanf(new_lines{ii},'%d%s%g%g%g%g%g%g');
end
% remove the character ('G') column:
data(:,2) = [];
% check the result:
format longG
disp(data)
1 Comment
Rodrigo Martín Ortiz
on 3 Oct 2022
Hello, I believe I have a very similar task in my hands to the original poster.
Firstly, your code has been very helpful in order to understand the process, since I've never had to deal with reading such kinds of files yet.
However, when running (I got the same NASTRAN .pch file, which I attach) I obtain a dimensions error on this line:
data(ii,:) = sscanf(new_lines{ii},'%d%s%g%g%g%g%g%g');
Ive tried removing the CONT line completely, since I dont need it for my application. However, when "sending" the new_lines cell array to the data matrix, I get these weird dimensions error. I think I may not be understanding the second part of the sscanf function.
Since the original poster did not attach the file, which I imagine must be very useful in order to get an accurate answer, I will do it, although in a txt. Hope it helps.
Help would be very much appreciated. Thank you.
See Also
Categories
Find more on Data Type Identification in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!