Textscan MULTIPLE DELIM ARRAY and rearrange

2 visualizzazioni (ultimi 30 giorni)
Philip
Philip il 26 Set 2018
Commentato: Bish Erbas il 26 Set 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!

Risposte (2)

Stephen23
Stephen23 il 26 Set 2018
Modificato: Stephen23 il 26 Set 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 il 26 Set 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

Prodotti


Release

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by