Textscan MULTIPLE DELIM ARRAY and rearrange

1 次查看(过去 30 天)
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

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by