How to read a text file and save it as different variables
2 views (last 30 days)
Show older comments
Hi,
I have a text file in the following format:
String line
String line
.Sample 1 0 0 0
5441.45 5454.52 5425.85 742.95
512.12 9894.21 4511.45 78921.45
.Sample 2 0 0 0
45961.45 8562.45 859.24 9453.14
845.52 6896.25 1236.45 9856.23
I have 10 such sample numbers and each sample has around 100 rows of numeric data. I want to read and save the data listed under each sample number as different variables. For example, all the data under Sample 1 0 0 0 as A, all the data under Sample 2 0 0 0 as B and so on. May I know how can I do that and which will be the best function to use.
1 Comment
Stephen23
on 21 Apr 2022
"For example, all the data under Sample 1 0 0 0 as A, all the data under Sample 2 0 0 0 as B and so on."
That makes accessing your data more complex, and forces you into writing slow, complex, inefficient code:
"May I know how can I do that and which will be the best function to use."
The neat, simple, and very efficient approach is to use indexing or fieldnames.
If you upload a sample file by clicking the paperclip button then someone can help you with this.
Accepted Answer
Mathieu NOE
on 21 Apr 2022
hello
I saved you short text from the post in a file and started some coding
nota this code contains also an alternative to readlines if you have an older release
see the results below :
data is a 2 cell array containing your 2 data :
>> data{1}
2×1 cell array
{'5441.45 5454.52 5425.85 742.95' }
{'512.12 9894.21 4511.45 78921.45'}
>> data{2}
2×1 cell array
{'45961.45 8562.45 859.24 9453.14'}
{'845.52 6896.25 1236.45 9856.23' }
code
%%%%%%%% main code %%%%%%%%%
clc
clearvars
filename = 'test.txt';
str = "Sample ";
[data] = myfunction_read(filename,str);
%%%%%%% functions %%%%%%%%%
function lines = my_readlines(filename)
% work around for earlier matlab releases (not having readlines)
lines = regexp(fileread(filename), '\r?\n', 'split');
if isempty(lines{end}); lines(end) = []; end %end of file correction
end
%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = myfunction_read(filename,str)
lines = my_readlines(filename);
% init data
count = 0;
flag = 0;
k = 0;
line_index = 1;
for ci = 1:numel(lines)
ll = lines(ci);
if contains(ll,str) %
line_index = ci;
flag = 1;
k = 0;
count = count+1;
end
if flag == 1 && ci >= line_index+1
k = k +1;
data{count}(k,:) = ll;
end
end
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!