How to read multiple matrices separately from .txt file
17 views (last 30 days)
Show older comments
Here is a .txt file like
matrixdata
matrix1
BEGIN
111
111
.
.
.
111
END
matrix2
BEGIN
222
222
222
.
.
.
222
END
There are several matrices and each is between "BIGIN" and "END" string.
I tried reading this by using "readmatrix" function.
Then, matrices were combined and read as one matrix like
111
111
.
.
.
111
222
222
222
.
.
.
222
Is there any good way to read matrices separately for every "BIGIN" and "END"?
0 Comments
Accepted Answer
Karim
on 17 Jun 2022
Edited: Karim
on 17 Jun 2022
Since it's not clear whether or not these matrices have the same dimensions, you can try to save them in a cell array.
See below for some example code, hope it helps
Best regards
% link to the text file
fileID = fopen('MatrixExample.txt');
% read the whole file, interpret each line as a string
MyText = textscan(fileID, '%s%[^\n\r]', 'Delimiter', '', 'WhiteSpace', '', 'ReturnOnError', false);
% first the start locations
StartLineIdx = cellfun(@(x) contains(x, "BEGIN"),MyText(:,1),'uni',0);
StartLineIdx = find(StartLineIdx{1}) + 1;
% now find the stop locations of each data block
StopLineIdx = cellfun(@(x) contains(x, "END"),MyText(:,1),'uni',0);
StopLineIdx = find(StopLineIdx{1}) - 1;
% Allocate the cell array
MyData = cell(numel(StartLineIdx),1);
% Get the data
for i = 1:numel(StartLineIdx)
MyData{i} = cellfun(@(x) textscan(x,'%f','Delimiter', '\t','WhiteSpace','', 'ReturnOnError',false),MyText{1}(StartLineIdx(i):StopLineIdx(i)));
MyData{i} = cellfun(@transpose,MyData{i},'UniformOutput',false);
MyData{i} = cell2mat(MyData{i});
end
Matrix_1 = MyData{1} % this is the first matrix
Matrix_2 = MyData{2} % this is the second matrix
3 Comments
Karim
on 17 Jun 2022
Yes, however the code becomes a bit more complicated.
I updated the example text file and also the code in the answer.
More Answers (0)
See Also
Categories
Find more on Large Files and Big Data 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!