How can i read the line above a certain position?
2 views (last 30 days)
Show older comments
Jiahong Zou
on 26 Jun 2023
Answered: Joe Vinciguerra
on 26 Jun 2023
This is how the Nastran file looks like
$$ PSHELL Data
$
$HMNAME PROP 5101090"PSHELL_5101090" 4
$HWCOLOR PROP 5101090 44
PSHELL 510109096069002VAR0000696069002 96069002
$INSERT_PSHELL
I want to read the line above $INSERT_PSHELL. So i have ChatGPT part of this code written for me, which didn't work at all
function [PID, IDENT] = addPSHELL(inputDir, fileName, elementList)
%% function add exact many PSHELL properties as elements in element list
NumberToAdd = numel(elementList);
% Read the original file
fid = fopen(fullfile(inputDir, fileName), 'rt');
if fid == -1
error('Failed to open the file.');
end
% Move to the position where identifier is
while ~feof(fid)
line = fgetl(fid);
% Check if the line contains the identifier and move
if contains(line, '$INSERT_PSHELL')
IdentifierPosition = ftell(fid);
break;
end
end
% Read the last PSHELL to get PID
fseek(fid, IdentifierPosition, 'bof');
while ftell(fid) > 0
fseek(fid, -1, 'cof'); % Move back one byte
% Check if the previous byte is a newline character
if fread(fid, 1, 'char') == 10
break; % Found the line above
end
fseek(fid, -1, 'cof'); % Move back one more byte
end
lineAbove = fgetl(fid);
if ~(rem(length(lineAbove), 8) == 0)
error('the line above is not 8 multiples digit long')
end
% Break the line into 8-digit pieces
for i = 1:(length(lineAbove) \ 8)
lineAbove{i} = lineAbove(1+8*i : 8*i); % PSHELL PID MID1 T MID2 .....
end
0 Comments
Accepted Answer
Joe Vinciguerra
on 26 Jun 2023
Replace "file_name" with whatever the name of your file is:
f = readlines(file_name); % read the file
k = find(f == "$INSERT_PSHELL"); % find the line number that matches your criteria
result = f(k-1); % this is the text on the line above it
0 Comments
More Answers (0)
See Also
Categories
Find more on PID Controller Tuning 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!