Extract rows from a text file and create array
4 次查看(过去 30 天)
显示 更早的评论
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
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
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
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:
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Large Files and Big Data 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!