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
  1 件のコメント
Bish Erbas
Bish Erbas 2018 年 9 月 26 日
Elegant!

サインインしてコメントする。


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 Center および File ExchangeLarge 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