Extract rows from a text file and create array

조회 수: 19 (최근 30일)
Syed Rizvi
Syed Rizvi 2022년 3월 29일
답변: Omega 2023년 9월 25일
I have a text file called horizon as shown below. I want to extract the data into cells but am not sure where to start. this is the code so far
function data = loaddata(filename)
disp(filename)
filename = strcat(filename,'.txt');
fid = fopen(filename,'rt');
if fid ~= -1
line = '';
while ~feof(fid) && ~strcmp(line,'$$SOE')
line = fgetl(fid);
end
data = cell(1000,3); % Preallocate
num = 0;
while ~feof(fid)
line = fgetl(fid);
if strcmp(line,'$$EOE') % Sentinel
break % while
end
num = num+1;
if size(data,1) < num
disp(size(data,1))
data{2*end,1} = []; % Allocate
end
data(num,:) = str2cell(line);
end
data = data(1:num,:); % Truncate
fclose(fid);
disp(num)
else
data = {}; % File open failure
end
end
function cellrow = str2cell(fid)
numdate = textscan(fid, '%*s', 'HeaderLines', 1);
  댓글 수: 2
Jan
Jan 2022년 3월 29일
Which data do you want to import in which format? Why cells?
Please post an example file. A screen shot is less useful, exspecially, if it is hard to read.
Mathieu NOE
Mathieu NOE 2022년 3월 29일
hello
if you want us to help you , maybe it would be great to share the txt file and the code + some explanations about what you want to retrieve.
all the best

댓글을 달려면 로그인하십시오.

답변 (1개)

Omega
Omega 2023년 9월 25일
Hi Syed,
I understand that you would like to extract the variables JDTDB, Calendar Data (TDB), X, Y and Z into a cell array. This can be achieved through the utilization of MATLAB's strtrim and strsplit functions.
Below is an illustrative code snippet that accomplishes the intended task:
data = loaddata(horizon_results);
function data = loaddata(filename)
disp(filename)
filename = strcat(filename, '.txt');
fid = fopen(filename, 'rt');
if fid ~= -1
line = '';
while ~feof(fid) && ~strcmp(line, '$$SOE')
line = fgetl(fid);
end
data = cell(1000, 5); % Preallocate
num = 0;
while ~feof(fid)
line = fgetl(fid);
if strcmp(line, '$$EOE') % Sentinel
break; % Exit the loop
end
num = num + 1;
if size(data, 1) < num
disp(size(data, 1))
data{2 * end, 1} = []; % Allocate more space
end
data(num, :) = str2cell(line);
end
data = data(1:num, :); % Truncate
fclose(fid);
disp(num)
else
data = {}; % File open failure
end
end
function cellrow = str2cell(line)
% Remove any extra whitespaces
line = strtrim(line);
% Split the input line by commas
parts = strsplit(line, ',');
% Take the first 5 cells
cellrow = parts(1:5);
end
If you’d like to learn more, you can refer to the following documentation links:

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by