Textscan MULTIPLE DELIM ARRAY and rearrange

1 view (last 30 days)
Philip
Philip on 26 Sep 2018
Commented: Bish Erbas on 26 Sep 2018
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!

Answers (2)

Stephen23
Stephen23 on 26 Sep 2018
Edited: Stephen23 on 26 Sep 2018
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 on 26 Sep 2018
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

Categories

Find more on Large Files and Big Data in Help Center and File Exchange

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!