How to read a text file and save it as different variables

조회 수: 15 (최근 30일)
Zee
Zee 2022년 4월 21일
답변: Mathieu NOE 2022년 4월 21일
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
Stephen23
Stephen23 2022년 4월 21일
"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.

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

채택된 답변

Mathieu NOE
Mathieu NOE 2022년 4월 21일
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개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

제품


릴리스

R2011b

Community Treasure Hunt

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

Start Hunting!

Translated by