how do I extract subsets from a vector
조회 수: 9 (최근 30일)
이전 댓글 표시
Hello,
I have a vector of the size [70397,2]. It has a title of 2 rows and some text 4 rows between the each data set (2x1801 each). This means a total of 39 sets.
I neet to extract the second column set into a matrix of [39,1801] size.
What would be the most efficient way to do it (I have 100 data sets similar to this one to process)
Thank you
댓글 수: 3
답변 (1개)
dpb
2023년 1월 17일
편집: dpb
2023년 1월 17일
One way just using the form of the file...
S=readlines('yourfile.txt'); % import as string array
ixFrom=find(startsWith(S,"# From:")); % index to beginning each section
sizeSection=str2double(S(ixFrom(1)+1)); % size of each group -- all must be same per Q? spec
isFrom=ixFrom+2; % adjust start of offset from header, count records
for i=1:numel(isFrom)
i1=isFrom(i); i2=i1+sizeSection-1; % start, stop records each section
tmp=str2double(split(S(i1:i2))); % convert to numeric array
if i==1
A=tmp; % save first set; keep time as well for first set
else
A=[A tmp(:,2)]; % append second column subsequent
end
end
Caution, air code, watch out for mismatched/missing paren's, etc., etc., etc., ...
This will return one extra column over the requested; if you really, really don't want the time(?) data as well at all, then just remove the special case and start off with
A=[];
The above uses dynamic reallocation; for no larger files than these the performance hit won't be bad compared to trying to reallocate. Or, you could use a cell array for the intermediary and then cell2mat
ADDENDUM:
For early releases predating readlines, use
S=string(textread('yourfile.txt','%s','delimiter','\n','whitespace',''));
댓글 수: 4
dpb
2023년 1월 17일
Didn't notice the release, sorry...in that case take an intermediary step first...
S=string(textread('yourfile.txt', '%s', 'delimiter', '\n','whitespace', ''));
The editor will complain that textread is not recommended, use textscan instead, but while textscan is somewhat more powerful, it's more of a pain to use because it doesn't accept a filename; you first have to open a file handle with fopen and then fclose it when done.
The above brings in the file a cellstr() array, then converts that to the string array to be consistent with remaining existent code posted.
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!