How to read multiple matrices separately from .txt file

8 Ansichten (letzte 30 Tage)
亮介 桶谷
亮介 桶谷 am 17 Jun. 2022
Kommentiert: 亮介 桶谷 am 17 Jun. 2022
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"?

Akzeptierte Antwort

Karim
Karim am 17 Jun. 2022
Bearbeitet: Karim am 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_1 = 3×2
111 112 111 116 111 112
Matrix_2 = MyData{2} % this is the second matrix
Matrix_2 = 4×1
222 222 222 222
  3 Kommentare
Karim
Karim am 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.
亮介 桶谷
亮介 桶谷 am 17 Jun. 2022
It works well for 2d matrix!!!
Thank you for your kind cooperation!!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by