Extract rows from a text file and create array

4 ビュー (過去 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 Center および File ExchangeLarge Files and Big Data についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by