How can i read the line above a certain position?

조회 수: 2 (최근 30일)
Jiahong Zou
Jiahong Zou 2023년 6월 26일
답변: Joe Vinciguerra 2023년 6월 26일
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

채택된 답변

Joe Vinciguerra
Joe Vinciguerra 2023년 6월 26일
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개)

카테고리

Help CenterFile Exchange에서 PID Controller Tuning에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by