Clear Filters
Clear Filters

Extract rows from a text file and create array

4 views (last 30 days)
Syed Rizvi
Syed Rizvi on 29 Mar 2022
Answered: Divit on 25 Sep 2023
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 Comments
Jan
Jan on 29 Mar 2022
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 on 29 Mar 2022
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

Sign in to comment.

Answers (1)

Divit
Divit on 25 Sep 2023
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:

Tags

Community Treasure Hunt

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

Start Hunting!