Textscan MULTIPLE DELIM ARRAY and rearrange

조회 수: 1 (최근 30일)
Philip
Philip 2018년 9월 26일
댓글: Bish Erbas 2018년 9월 26일
How do I import the following .txt file into an array in matlab:
NOTE: The brackets are tripping up my attempts.
.txt file
[ [ 1,2,3,4],[1,2,3,4],[1,2,3,4] ]
matlab output
4x3 array =
1 1 1
2 2 2
3 3 3
4 4 4
Note How the original data is groups of COLUMN DATA in sequential row-order in .txt file.
Thanks!

답변 (2개)

Stephen23
Stephen23 2018년 9월 26일
편집: Stephen23 2018년 9월 26일
This automatically adjusts to the size of the input data. You could easily adapt it to work with either sscanf:
>> S = '[ [ 1,2,3,4],[1,2,3,4],[1,2,3,4] ]'; % use FILEREAD
>> S = strrep(S,' ',''); % get rid of spaces.
>> C = nnz(S=='[')-1;
>> T = nnz(S==',')+1;
>> R = T./C;
>> F = repmat(',%f',1,R);
>> F = sprintf('[%s],',F(2:end));
>> M = sscanf(S(2:end),F,[R,C])
M =
1 1 1
2 2 2
3 3 3
4 4 4
or with textscan:
>> F = repmat('%f',1,R);
>> C = textscan(S,F, 'MultipleDelimsAsOne',true, 'Delimiter',',[', 'EndOfLine',']');
>> M = [C{:}].'
M =
1 1 1
2 2 2
3 3 3
4 4 4

Bish Erbas
Bish Erbas 2018년 9월 26일
Just rename untitled.txt. Is this something you were looking for?
% [ [ 1,2,3,4],[1,2,3,4],[1,2,3,4] ]
f = fopen('untitled.txt');
C = textscan(f,'%f','Delimiter','],[','EmptyValue',Inf);
fclose(f);
V = C{:};
V = V(~isinf(V))';
A = reshape(V,4,3)'
Output:
A =
1 2 3 4
1 2 3 4
1 2 3 4

카테고리

Help CenterFile Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by