Find empty line in text file and build array

조회 수: 3 (최근 30일)
Sergio Yanez-Pagans
Sergio Yanez-Pagans 2021년 7월 9일
댓글: Sergio Yanez-Pagans 2021년 7월 9일
Hello everyone, I need help with this, please. If I have a text file (.txt) which contains the following:
1 1
1 1
2 2
2 2
3 3
3 3
I want to read this file and save the data into an array the saves the data in a new dimension everytime it finds an empty line. What I mean is that I would like to save all the data into 'array' such that:
array(1,:) = [1 1;1 1]
array(2,:) = [2 2;2 2]
array(3,:) = [3 3;3 3]
Thank you for your time!

채택된 답변

Walter Roberson
Walter Roberson 2021년 7월 9일
if isunix()
%fake data
S = sprintf('1 1\n1 1\n\n2 2\n2 2\n\n3 3\n3 3\n')
else
S = fileread('YourFile.txt');
end
S =
'1 1 1 1 2 2 2 2 3 3 3 3 '
blocks = regexp(S, '\r?\n\r?\n', 'split')
blocks = 1×3 cell array
{'1 1↵1 1'} {'2 2↵2 2'} {'3 3↵3 3↵'}
block_values = cellfun(@(s) cell2mat(textscan(s, '')), blocks, 'uniform', 0)
block_values = 1×3 cell array
{2×2 double} {2×2 double} {2×2 double}
array = cat(3, block_values{:})
array =
array(:,:,1) = 1 1 1 1 array(:,:,2) = 2 2 2 2 array(:,:,3) = 3 3 3 3

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by